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. */ #include "hitls_build.h" #ifdef HITLS_TLS_FEATURE_SESSION_TICKET #include <stdbool.h> #include "securec.h" #include "tlv.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "hitls_error.h" #include "session_enc.h" #include "session_type.h" #include "cert_mgr_ctx.h" #include "cert_method.h" #include "parse_common.h" #define MAX_PSK_IDENTITY_LEN 0xffff #ifdef HITLS_TLS_FEATURE_SNI #define MAX_HOST_NAME_LEN 0xff #endif typedef int32_t (*PfuncDecSessionObjFunc)(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen); typedef struct { SessionObjType type; PfuncDecSessionObjFunc func; } SessObjDecFunc; static int32_t DecSessObjVersion(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint16_t version = 0; BSL_Tlv tlv = {0}; tlv.length = sizeof(version); tlv.value = (uint8_t *)&version; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_VERSION_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15993, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session version fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_VERSION_FAIL; } sess->version = version; return HITLS_SUCCESS; } static int32_t DecSessObjCipherSuite(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint16_t cipherSuite = 0; BSL_Tlv tlv = {0}; tlv.length = sizeof(cipherSuite); tlv.value = (uint8_t *)&cipherSuite; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_CIPHER_SUITE_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15994, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session cipher suite fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_CIPHER_SUITE_FAIL; } sess->cipherSuite = cipherSuite; return HITLS_SUCCESS; } static int32_t DecSessObjMasterSecret(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; BSL_Tlv tlv = {0}; tlv.length = MAX_MASTER_KEY_SIZE; tlv.value = sess->masterKey; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_MASTER_SECRET_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15995, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session master secret fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_MASTER_SECRET_FAIL; } sess->masterKeySize = tlv.length; return HITLS_SUCCESS; } static int32_t DecSessObjStartTime(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint64_t startTime = 0; BSL_Tlv tlv = {0}; tlv.length = sizeof(startTime); tlv.value = (uint8_t *)&startTime; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_START_TIME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15998, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session start time fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_START_TIME_FAIL; } sess->startTime = startTime; return HITLS_SUCCESS; } static int32_t DecSessObjTimeout(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint64_t timeout = 0; BSL_Tlv tlv = {0}; tlv.length = sizeof(timeout); tlv.value = (uint8_t *)&timeout; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_TIME_OUT_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15999, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session timeout fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_TIME_OUT_FAIL; } sess->timeout = timeout; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SNI static int32_t DecSessObjHostName(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint32_t offset = sizeof(uint32_t); // The length has been verified at the upper layer and must be greater than 8 bytes. uint32_t tlvLen = BSL_ByteToUint32(&data[offset]); if (tlvLen > MAX_HOST_NAME_LEN || tlvLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16701, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "tlvLen error", 0, 0, 0, 0); return HITLS_SESS_ERR_DEC_HOST_NAME_FAIL; } uint8_t *hostName = BSL_SAL_Calloc(1u, tlvLen); if (hostName == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16000, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc hostName fail when decode session obj host name.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } BSL_Tlv tlv = {0}; tlv.length = tlvLen; tlv.value = hostName; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_SAL_FREE(hostName); BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_HOST_NAME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16001, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session host name fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_HOST_NAME_FAIL; } sess->hostName = tlv.value; sess->hostNameSize = tlv.length; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SNI */ static int32_t DecSessObjSessionIdCtx(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; BSL_Tlv tlv = {0}; tlv.length = HITLS_SESSION_ID_MAX_SIZE; tlv.value = sess->sessionIdCtx; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_SESSION_ID_CTX_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16002, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session session id ctx fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_SESSION_ID_CTX_FAIL; } sess->sessionIdCtxSize = tlv.length; return HITLS_SUCCESS; } static int32_t DecSessObjSessionId(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; BSL_Tlv tlv = {0}; tlv.length = HITLS_SESSION_ID_MAX_SIZE; tlv.value = sess->sessionId; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_SESSION_ID_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16003, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session session id fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_SESSION_ID_FAIL; } sess->sessionIdSize = tlv.length; return HITLS_SUCCESS; } static int32_t DecSessObjExtendMasterSecret(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint8_t haveExtMasterSecret = 0; BSL_Tlv tlv = {0}; tlv.length = sizeof(haveExtMasterSecret); tlv.value = &haveExtMasterSecret; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_EXT_MASTER_SECRET_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16004, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session extend master secret fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_EXT_MASTER_SECRET_FAIL; } sess->haveExtMasterSecret = (bool)haveExtMasterSecret; return HITLS_SUCCESS; } static int32_t DecSessObjVerifyResult(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint32_t verifyResult = 0; BSL_Tlv tlv = {0}; tlv.length = sizeof(verifyResult); tlv.value = (uint8_t *)&verifyResult; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_VERIFY_RESULT_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16005, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session verify result fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_VERIFY_RESULT_FAIL; } sess->verifyResult = (int32_t)verifyResult; return HITLS_SUCCESS; } static int32_t ParseBufToCert(HITLS_Session *sess, const uint8_t *buf, uint32_t bufLen) { uint32_t offset = 0; ParsePacket pkt = {.ctx = NULL, .buf = buf, .bufLen = bufLen, .bufOffset = &offset}; /* Obtain the certificate length */ uint32_t certLen = 0; int32_t ret = ParseBytesToUint24(&pkt, &certLen); if (ret != HITLS_SUCCESS || (certLen != (pkt.bufLen - CERT_LEN_TAG_SIZE))) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16260, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode certLen fail.", 0, 0, 0, 0); return HITLS_PARSE_INVALID_MSG_LEN; } #ifndef HITLS_TLS_FEATURE_PROVIDER CERT_MgrCtx *certMgrCtx = sess->certMgrCtx; if (certMgrCtx == NULL || certMgrCtx->method.certParse == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16261, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certMgrCtx or certMgrCtx->method.certParse is null.", 0, 0, 0, 0); return HITLS_NULL_INPUT; } /* Parse the first device certificate. */ HITLS_CERT_X509 *cert = certMgrCtx->method.certParse(NULL, &pkt.buf[*pkt.bufOffset], certLen, TLS_PARSE_TYPE_BUFF, TLS_PARSE_FORMAT_ASN1); #else HITLS_CERT_X509 *cert = SAL_CERT_X509Parse(LIBCTX_FROM_SESSION_CTX(sess), ATTRIBUTE_FROM_SESSION_CTX(sess), NULL, &pkt.buf[*pkt.bufOffset], certLen, TLS_PARSE_TYPE_BUFF, TLS_PARSE_FORMAT_ASN1); #endif if (cert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16262, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse peer eecert error", 0, 0, 0, 0); return HITLS_CERT_ERR_PARSE_MSG; } CERT_Pair *newCertPair = BSL_SAL_Calloc(1u, sizeof(CERT_Pair)); if (newCertPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16263, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "peer cert malloc fail.", 0, 0, 0, 0); SAL_CERT_X509Free(cert); return HITLS_MEMALLOC_FAIL; } newCertPair->cert = cert; sess->peerCert = newCertPair; return HITLS_SUCCESS; } static int32_t DecSessObjPeerCert(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { (void)type; uint32_t offset = sizeof(uint32_t); // The length has been verified at the upper layer and must be greater than 8 bytes. uint32_t tlvLen = BSL_ByteToUint32(&data[offset]); offset += sizeof(uint32_t); if ((tlvLen == 0) || (tlvLen > length - offset)) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_PEER_CERT_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16264, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode peercert fail.", 0, 0, 0, 0); return HITLS_SESS_ERR_DEC_PEER_CERT_FAIL; } *readLen = tlvLen + offset; return ParseBufToCert(sess, &data[offset], tlvLen); } static int32_t DecSessObjTicketAgeAdd(HITLS_Session *sess, SessionObjType type, const uint8_t *data, uint32_t length, uint32_t *readLen) { int32_t ret; uint32_t ticketAgeAdd = 0; BSL_Tlv tlv = {0}; tlv.length = sizeof(ticketAgeAdd); tlv.value = (uint8_t *)&ticketAgeAdd; ret = BSL_TLV_Parse(type, data, length, &tlv, readLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DEC_START_TIME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15998, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decode session TicketAgeAdd fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_DEC_START_TIME_FAIL; } sess->ticketAgeAdd = ticketAgeAdd; return HITLS_SUCCESS; } /* * Decoding function list. * Ensure that the sequence of decode and encode types is the same. */ static const SessObjDecFunc OBJ_LIST[] = { {SESS_OBJ_VERSION, DecSessObjVersion}, {SESS_OBJ_CIPHER_SUITE, DecSessObjCipherSuite}, {SESS_OBJ_MASTER_SECRET, DecSessObjMasterSecret}, {SESS_OBJ_PEER_CERT, DecSessObjPeerCert}, {SESS_OBJ_START_TIME, DecSessObjStartTime}, {SESS_OBJ_TIMEOUT, DecSessObjTimeout}, #ifdef HITLS_TLS_FEATURE_SNI {SESS_OBJ_HOST_NAME, DecSessObjHostName}, #endif {SESS_OBJ_SESSION_ID_CTX, DecSessObjSessionIdCtx}, {SESS_OBJ_SESSION_ID, DecSessObjSessionId}, {SESS_OBJ_SUPPORT_EXTEND_MASTER_SECRET, DecSessObjExtendMasterSecret}, {SESS_OBJ_VERIFY_RESULT, DecSessObjVerifyResult}, {SESS_OBJ_AGE_ADD, DecSessObjTicketAgeAdd}, }; int32_t SESS_Decode(HITLS_Session *sess, const uint8_t *data, uint32_t length) { if (sess == NULL || data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16006, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESS_Decode input parameter is NULL.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } int32_t ret; uint32_t index; const uint8_t *curPos = data; uint32_t offset = 0; uint32_t readLen = 0; for (index = 0; index < sizeof(OBJ_LIST) / sizeof(SessObjDecFunc); index++) { if (length - offset < TLV_HEADER_LENGTH) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DECODE_TICKET); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16009, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESS_Decode length error, offset is %u, length is %u.", offset, length, 0, 0); return HITLS_SESS_ERR_DECODE_TICKET; } uint32_t type = BSL_ByteToUint32(curPos); if (OBJ_LIST[index].type != type) { continue; } readLen = 0; ret = OBJ_LIST[index].func(sess, OBJ_LIST[index].type, curPos, length - offset, &readLen); if (ret != HITLS_SUCCESS) { return ret; } offset += readLen; curPos += readLen; } if (offset != length) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_DECODE_TICKET); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16007, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESS_Decode fail, offset is %u, length is %u.", offset, length, 0, 0); return HITLS_SESS_ERR_DECODE_TICKET; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */
2301_79861745/bench_create
tls/feature/session/src/session_dec.c
C
unknown
15,397
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_SESSION_TICKET #include "tlv.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_bytes.h" #include "bsl_list.h" #include "bsl_sal.h" #include "hitls_error.h" #include "session_type.h" #include "cert_mgr_ctx.h" #include "session_enc.h" #include "cert_method.h" typedef int32_t (*PfuncEncSessionObjFunc)(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen); typedef struct { SessionObjType type; PfuncEncSessionObjFunc func; } SessObjEncFunc; static int32_t EncSessObjVersion(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; uint16_t version = sess->version; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sizeof(version); tlv.value = (uint8_t *)&version; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_VERSION_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15992, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session version fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_VERSION_FAIL; } return HITLS_SUCCESS; } static int32_t EncSessObjCipherSuite(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; uint16_t cipherSuite = sess->cipherSuite; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sizeof(cipherSuite); tlv.value = (uint8_t *)&cipherSuite; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_CIPHER_SUITE_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15982, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session cipher suite fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_CIPHER_SUITE_FAIL; } return HITLS_SUCCESS; } static int32_t EncSessObjMasterSecret(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sess->masterKeySize; tlv.value = (uint8_t *)(uintptr_t)(sess->masterKey); if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_MASTER_SECRET_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15983, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session master secret fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_MASTER_SECRET_FAIL; } return HITLS_SUCCESS; } static int32_t EncSessObjStartTime(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; uint64_t startTime = sess->startTime; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sizeof(startTime); tlv.value = (uint8_t *)&startTime; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_START_TIME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15985, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session start time fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_START_TIME_FAIL; } return HITLS_SUCCESS; } static int32_t EncSessObjTimeout(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; uint64_t timeout = sess->timeout; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sizeof(timeout); tlv.value = (uint8_t *)&timeout; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_TIME_OUT_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15986, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session timeout fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_TIME_OUT_FAIL; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SNI static int32_t EncSessObjHostName(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { if (sess->hostNameSize == 0) { return HITLS_SUCCESS; } int ret; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sess->hostNameSize; tlv.value = (uint8_t *)sess->hostName; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_HOST_NAME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15987, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session host name fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_HOST_NAME_FAIL; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SNI */ static int32_t EncSessObjSessionIdCtx(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { if (sess->sessionIdCtxSize == 0) { return HITLS_SUCCESS; } int ret; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sess->sessionIdCtxSize; tlv.value = (uint8_t *)(uintptr_t)(sess->sessionIdCtx); if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_SESSION_ID_CTX_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15988, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session session id ctx fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_SESSION_ID_CTX_FAIL; } return HITLS_SUCCESS; } static int32_t EncSessObjSessionId(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { if (sess->sessionIdSize == 0) { return HITLS_SUCCESS; } int ret; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sess->sessionIdSize; tlv.value = (uint8_t *)(uintptr_t)(sess->sessionId); if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_SESSION_ID_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15989, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session session id fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_SESSION_ID_FAIL; } return HITLS_SUCCESS; } static int32_t EncSessObjExtendMasterSecret(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; uint8_t haveExtMasterSecret = (uint8_t)sess->haveExtMasterSecret; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sizeof(haveExtMasterSecret); tlv.value = (uint8_t *)&haveExtMasterSecret; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_EXT_MASTER_SECRET_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15990, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session extend master secret fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_EXT_MASTER_SECRET_FAIL; } return HITLS_SUCCESS; } static int32_t EncSessObjVerifyResult(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; int32_t verifyResult = sess->verifyResult; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sizeof(verifyResult); tlv.value = (uint8_t *)&verifyResult; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_VERIFY_RESULT_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15991, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session verify result fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_VERIFY_RESULT_FAIL; } return HITLS_SUCCESS; } static int32_t PackCertToBuf(const HITLS_Session *sess, uint8_t *buf, uint32_t bufLen) { CERT_Pair *peerCert = sess->peerCert; HITLS_CERT_X509 *cert = peerCert->cert; uint32_t encodeLen = 0; #ifndef HITLS_TLS_FEATURE_PROVIDER CERT_MgrCtx *mgrCtx = sess->certMgrCtx; if (mgrCtx->method.certEncode == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16254, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "mgrCtx->method.certEncode is null.", 0, 0, 0, 0); return HITLS_NULL_INPUT; } /* Write the certificate data. */ int32_t ret = mgrCtx->method.certEncode(NULL, cert, &buf[CERT_LEN_TAG_SIZE], bufLen - CERT_LEN_TAG_SIZE, &encodeLen); #else int32_t ret = SAL_CERT_X509Encode(NULL, cert, &buf[CERT_LEN_TAG_SIZE], bufLen - CERT_LEN_TAG_SIZE, &encodeLen); #endif if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16255, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certEncode error.", 0, 0, 0, 0); return HITLS_CERT_ERR_ENCODE_CERT; } if (bufLen - CERT_LEN_TAG_SIZE != encodeLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16256, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encodeLen error.", 0, 0, 0, 0); return HITLS_CERT_ERR_ENCODE_CERT; } BSL_Uint24ToByte(encodeLen, buf); return HITLS_SUCCESS; } static uint32_t GetPeertCertSize(const HITLS_Session *sess) { uint32_t certLen = 0; CERT_Pair *peerCert = sess->peerCert; #ifndef HITLS_TLS_FEATURE_PROVIDER CERT_MgrCtx *mgrCtx = sess->certMgrCtx; if (mgrCtx == NULL || mgrCtx->method.certCtrl == NULL || peerCert->cert == NULL) { return 0; } int32_t ret = mgrCtx->method.certCtrl(NULL, peerCert->cert, CERT_CTRL_GET_ENCODE_LEN, NULL, (void *)&certLen); #else int32_t ret = SAL_CERT_X509Ctrl(NULL, peerCert->cert, CERT_CTRL_GET_ENCODE_LEN, NULL, (void *)&certLen); #endif if (ret != HITLS_SUCCESS || certLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16257, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CERT_CTRL_GET_ENCODE_LEN error.", 0, 0, 0, 0); return 0; } return certLen + CERT_LEN_TAG_SIZE; } static int32_t EncSessObjPeerCert(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { CERT_Pair *peerCert = sess->peerCert; if (peerCert == NULL) { return HITLS_SUCCESS; } uint32_t bufLen = GetPeertCertSize(sess); if (bufLen == 0) { return HITLS_SUCCESS; } BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = bufLen; if (data == NULL) { /* If the input parameter is NULL, return the length after encoding. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } uint8_t *curPos = data; if ((length < TLV_HEADER_LENGTH) || (tlv.length > length - TLV_HEADER_LENGTH)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16258, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TLV build error: length = %u is not enough for tlv length = %u, tlv type = 0x%x.", length, tlv.length, tlv.type, 0); BSL_ERR_PUSH_ERROR(BSL_TLV_ERR_BAD_PARAM); return BSL_TLV_ERR_BAD_PARAM; } /* Write the TLV type */ BSL_Uint32ToByte(tlv.type, curPos); curPos += sizeof(uint32_t); /* Write the TLV length */ BSL_Uint32ToByte(tlv.length, curPos); curPos += sizeof(uint32_t); int32_t ret = PackCertToBuf(sess, curPos, tlv.length); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16265, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PackCertToBuf fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_PEER_CERT_FAIL; } *encLen = TLV_HEADER_LENGTH + tlv.length; return HITLS_SUCCESS; } static int32_t EncSessObjTicketAgeAdd(const HITLS_Session *sess, SessionObjType type, uint8_t *data, uint32_t length, uint32_t *encLen) { int ret; uint32_t ticketAgeAdd = sess->ticketAgeAdd; BSL_Tlv tlv = {0}; tlv.type = type; tlv.length = sizeof(ticketAgeAdd); tlv.value = (uint8_t *)&ticketAgeAdd; if (data == NULL) { /* If the input parameter is NULL, the length after encoding is returned. */ *encLen = sizeof(tlv.type) + sizeof(tlv.length) + tlv.length; return HITLS_SUCCESS; } ret = BSL_TLV_Pack(&tlv, data, length, encLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_ENC_VERIFY_RESULT_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16183, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode session TicketAgeAdd fail. ret %d", ret, 0, 0, 0); return HITLS_SESS_ERR_ENC_VERIFY_RESULT_FAIL; } return HITLS_SUCCESS; } /* * Encoding function list. * Ensure that the sequence of decode and encode types is the same. */ static const SessObjEncFunc OBJ_LIST[] = { {SESS_OBJ_VERSION, EncSessObjVersion}, {SESS_OBJ_CIPHER_SUITE, EncSessObjCipherSuite}, {SESS_OBJ_MASTER_SECRET, EncSessObjMasterSecret}, {SESS_OBJ_PEER_CERT, EncSessObjPeerCert}, {SESS_OBJ_START_TIME, EncSessObjStartTime}, {SESS_OBJ_TIMEOUT, EncSessObjTimeout}, #ifdef HITLS_TLS_FEATURE_SNI {SESS_OBJ_HOST_NAME, EncSessObjHostName}, #endif {SESS_OBJ_SESSION_ID_CTX, EncSessObjSessionIdCtx}, {SESS_OBJ_SESSION_ID, EncSessObjSessionId}, {SESS_OBJ_SUPPORT_EXTEND_MASTER_SECRET, EncSessObjExtendMasterSecret}, {SESS_OBJ_VERIFY_RESULT, EncSessObjVerifyResult}, {SESS_OBJ_AGE_ADD, EncSessObjTicketAgeAdd}, }; uint32_t SESS_GetTotalEncodeSize(const HITLS_Session *sess) { if (sess == NULL) { return 0; } uint32_t index; uint32_t offset = 0; uint32_t encLen = 0; for (index = 0; index < sizeof(OBJ_LIST) / sizeof(SessObjEncFunc); index++) { encLen = 0; /* This parameter is used only to obtain the encoded length and will not verified the returned value. */ (void)OBJ_LIST[index].func(sess, OBJ_LIST[index].type, NULL, 0, &encLen); offset += encLen; } return offset; } int32_t SESS_Encode(const HITLS_Session *sess, uint8_t *data, uint32_t length, uint32_t *usedLen) { if (sess == NULL || data == NULL || usedLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16008, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESS_Encode input parameter is NULL.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } int32_t ret; uint32_t index; uint8_t *curPos = data; uint32_t offset = 0; uint32_t encLen = 0; for (index = 0; index < sizeof(OBJ_LIST) / sizeof(SessObjEncFunc); index++) { encLen = 0; ret = OBJ_LIST[index].func(sess, OBJ_LIST[index].type, curPos, length - offset, &encLen); if (ret != HITLS_SUCCESS) { return ret; } offset += encLen; curPos += encLen; } *usedLen = offset; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */
2301_79861745/bench_create
tls/feature/session/src/session_enc.c
C
unknown
17,675
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_ENC_H #define SESSION_ENC_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif /** * Enumerated value of session information * Do not change the enumerated value. If need add the enumerated value, add at the end */ typedef enum { SESS_OBJ_VERSION = 0x0101, SESS_OBJ_CIPHER_SUITE = 0x0102, SESS_OBJ_MASTER_SECRET = 0x0103, SESS_OBJ_PEER_CERT = 0x0104, SESS_OBJ_START_TIME = 0x0106, SESS_OBJ_TIMEOUT = 0x0107, SESS_OBJ_HOST_NAME = 0x0108, SESS_OBJ_SESSION_ID_CTX = 0x0109, SESS_OBJ_SESSION_ID = 0x010A, SESS_OBJ_SUPPORT_EXTEND_MASTER_SECRET = 0x010B, SESS_OBJ_VERIFY_RESULT = 0x010C, SESS_OBJ_AGE_ADD = 0x010D, } SessionObjType; /** * @brief Obtain the length of the encoded SESS information * * @param sess [IN] sess structure * * @retval Length of the encoded data */ uint32_t SESS_GetTotalEncodeSize(const HITLS_Session *sess); /** * @brief Encode the SESS information to generate data * * @param sess [IN] sess structure * @param data [OUT] Packed data * @param length [IN] Maximum length of the data array * @param usedLen [OUT] Data length after packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESS_Encode(const HITLS_Session *sess, uint8_t *data, uint32_t length, uint32_t *usedLen); /** * @brief Decode data into SESS information * * @param sess [OUT] sess structure * @param data [IN] Data to be parsed * @param length [IN] Length of the data to be parsed * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESS_Decode(HITLS_Session *sess, const uint8_t *data, uint32_t length); #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
tls/feature/session/src/session_enc.h
C
unknown
2,309
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_SESSION #include <stdbool.h> #include "securec.h" #include "bsl_sal.h" #include "sal_time.h" #include "bsl_hash.h" #include "hitls_error.h" #include "session.h" #include "bsl_errno.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "crypt.h" #include "tls.h" #include "session_type.h" #include "session_mgr.h" #define SESSION_DEFAULT_TIMEOUT 7200u #ifdef HITLS_TLS_FEATURE_SESSION #define SESSION_DEFAULT_CACHE_SIZE 256u #endif #define SESSION_GERNERATE_RETRY_MAX_TIMES 10 #define SESSION_DEFAULT_HASH_BKT_SZIE 64u typedef struct { uint32_t sessionIdSize; uint8_t sessionId[HITLS_SESSION_ID_MAX_SIZE]; } SessionKey; /* For details about the SessKey hash function, see BSL_CstlHashCodeCalcStr */ static uint32_t SessKeyHashCodeCal(uintptr_t key, uint32_t bktSize) { if (bktSize == 0) { return 0; } SessionKey *tmpKey = (SessionKey *)key; uint32_t hashCode = BSL_HASH_CodeCalc(tmpKey, sizeof(SessionKey)); return hashCode % bktSize; } static bool SessKeyHashMacth(uintptr_t key1, uintptr_t key2) { SessionKey *tkey1 = (SessionKey *)key1; SessionKey *tkey2 = (SessionKey *)key2; if (memcmp(tkey1, tkey2, sizeof(SessionKey)) == 0) { return true; } return false; } /* Session key copy function, which returns the address for storing character strings */ static void *SessKeyDupFunc(void *src, size_t size) { if (src == NULL || size == 0) { return NULL; } SessionKey *dupKey = (SessionKey *)BSL_SAL_Dump(src, (uint32_t)size); return (void *)dupKey; } static void SessKeyFreeFunc(void *ptr) { BSL_SAL_FREE(ptr); return; } /* Session copy function */ static void *SessionDupFunc(void *src, size_t size) { (void)size; return (void *)HITLS_SESS_Dup((HITLS_Session *)src); } static void SessionFreeFunc(void *ptr) { HITLS_SESS_Free((HITLS_Session *)ptr); return; } TLS_SessionMgr *SESSMGR_New(HITLS_Lib_Ctx *libCtx) { TLS_SessionMgr *mgr = (TLS_SessionMgr *)BSL_SAL_Calloc(1u, sizeof(TLS_SessionMgr)); if (mgr == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16702, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } if (BSL_SAL_ThreadLockNew(&mgr->lock) != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16703, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ThreadLockNew fail", 0, 0, 0, 0); BSL_SAL_FREE(mgr); return NULL; } /* Prepare the default ticket key */ if (SAL_CRYPT_Rand(libCtx, mgr->ticketKeyName, sizeof(mgr->ticketKeyName)) != HITLS_SUCCESS || SAL_CRYPT_Rand(libCtx, mgr->ticketAesKey, sizeof(mgr->ticketAesKey)) != HITLS_SUCCESS || SAL_CRYPT_Rand(libCtx, mgr->ticketHmacKey, sizeof(mgr->ticketHmacKey)) != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16704, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Rand fail", 0, 0, 0, 0); BSL_SAL_ThreadLockFree(mgr->lock); BSL_SAL_FREE(mgr); return NULL; } // Apply for a hash table from mgr->hash ListDupFreeFuncPair keyFunc = {.dupFunc = SessKeyDupFunc, .freeFunc = SessKeyFreeFunc}; ListDupFreeFuncPair valueFunc = {.dupFunc = SessionDupFunc, .freeFunc = SessionFreeFunc}; mgr->hash = BSL_HASH_Create(SESSION_DEFAULT_HASH_BKT_SZIE, SessKeyHashCodeCal, SessKeyHashMacth, &keyFunc, &valueFunc); if (mgr->hash == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16705, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HASH_Create fail", 0, 0, 0, 0); BSL_SAL_ThreadLockFree(mgr->lock); BSL_SAL_FREE(mgr); return NULL; } #ifdef HITLS_TLS_FEATURE_SESSION mgr->sessCacheMode = HITLS_SESS_CACHE_SERVER; mgr->sessCacheSize = SESSION_DEFAULT_CACHE_SIZE; #endif mgr->sessTimeout = SESSION_DEFAULT_TIMEOUT; mgr->references = 1; return mgr; } /* Copy the number of references. The number of references increases by 1 */ TLS_SessionMgr *SESSMGR_Dup(TLS_SessionMgr *mgr) { if (mgr == NULL) { return NULL; } BSL_SAL_ThreadWriteLock(mgr->lock); mgr->references++; BSL_SAL_ThreadUnlock(mgr->lock); return mgr; } void SESSMGR_Free(TLS_SessionMgr *mgr) { if (mgr != NULL) { BSL_SAL_ThreadWriteLock(mgr->lock); mgr->references--; if (mgr->references > 0) { BSL_SAL_ThreadUnlock(mgr->lock); return; } BSL_SAL_ThreadUnlock(mgr->lock); // Delete all sessions BSL_HASH_Destory(mgr->hash); mgr->hash = NULL; BSL_SAL_ThreadLockFree(mgr->lock); BSL_SAL_FREE(mgr); } return; } void SESSMGR_SetTimeout(TLS_SessionMgr *mgr, uint64_t sessTimeout) { if (mgr != NULL) { BSL_SAL_ThreadWriteLock(mgr->lock); mgr->sessTimeout = sessTimeout; BSL_SAL_ThreadUnlock(mgr->lock); } return; } uint64_t SESSMGR_GetTimeout(TLS_SessionMgr *mgr) { if (mgr == NULL) { return SESSION_DEFAULT_TIMEOUT; } uint64_t sessTimeout; BSL_SAL_ThreadReadLock(mgr->lock); sessTimeout = mgr->sessTimeout; BSL_SAL_ThreadUnlock(mgr->lock); return sessTimeout; } #ifdef HITLS_TLS_FEATURE_SESSION void SESSMGR_SetCacheMode(TLS_SessionMgr *mgr, HITLS_SESS_CACHE_MODE mode) { if (mgr != NULL) { BSL_SAL_ThreadWriteLock(mgr->lock); mgr->sessCacheMode = mode; BSL_SAL_ThreadUnlock(mgr->lock); } return; } HITLS_SESS_CACHE_MODE SESSMGR_GetCacheMode(TLS_SessionMgr *mgr) { HITLS_SESS_CACHE_MODE mode; BSL_SAL_ThreadReadLock(mgr->lock); mode = mgr->sessCacheMode; BSL_SAL_ThreadUnlock(mgr->lock); return mode; } /* Set the maximum number of cache sessions */ void SESSMGR_SetCacheSize(TLS_SessionMgr *mgr, uint32_t sessCacheSize) { if (mgr != NULL) { BSL_SAL_ThreadWriteLock(mgr->lock); mgr->sessCacheSize = sessCacheSize; BSL_SAL_ThreadUnlock(mgr->lock); } return; } /* Obtain the maximum number of cached sessions. Ensure that the pointer is not NULL */ uint32_t SESSMGR_GetCacheSize(TLS_SessionMgr *mgr) { uint32_t sessCacheSize = 0u; BSL_SAL_ThreadReadLock(mgr->lock); sessCacheSize = mgr->sessCacheSize; BSL_SAL_ThreadUnlock(mgr->lock); return sessCacheSize; } #endif #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) void SESSMGR_InsertSession(TLS_SessionMgr *mgr, HITLS_Session *sess, bool isClient) { if (mgr == NULL || sess == NULL) { return; } BSL_SAL_ThreadReadLock(mgr->lock); HITLS_SESS_CACHE_MODE mode = mgr->sessCacheMode; BSL_SAL_ThreadUnlock(mgr->lock); SessionKey key = {0}; key.sessionIdSize = sizeof(key.sessionId); if (HITLS_SESS_GetSessionId(sess, key.sessionId, &(key.sessionIdSize)) != HITLS_SUCCESS) { return; } if (key.sessionIdSize == 0) { return; } if (mode == HITLS_SESS_CACHE_NO) { return; } if (isClient == true && mode == HITLS_SESS_CACHE_SERVER) { return; } if (isClient == false && mode == HITLS_SESS_CACHE_CLIENT) { return; } BSL_SAL_ThreadWriteLock(mgr->lock); if (BSL_HASH_Size(mgr->hash) < mgr->sessCacheSize) { /* Insert a session node */ BSL_HASH_Insert(mgr->hash, (uintptr_t)&key, sizeof(key), (uintptr_t)sess, 0); } else { BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15305, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "over sess cache size", 0, 0, 0, 0); } BSL_SAL_ThreadUnlock(mgr->lock); return; } #endif /* #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SESSION_ID /* Find the matching session */ HITLS_Session *SESSMGR_Find(TLS_SessionMgr *mgr, uint8_t *sessionId, uint8_t sessionIdSize) { if (mgr == NULL || sessionId == NULL || sessionIdSize == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16706, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return NULL; } BSL_SAL_ThreadReadLock(mgr->lock); HITLS_Session *sess = NULL; SessionKey key = {0}; key.sessionIdSize = sessionIdSize; if (memcpy_s(key.sessionId, sizeof(key.sessionId), sessionId, sessionIdSize) == EOK) { // Query the session corresponding to the key if (BSL_HASH_At(mgr->hash, (uintptr_t)&key, (uintptr_t *)&sess) != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15353, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "not find sess", 0, 0, 0, 0); sess = NULL; goto EXIT; } } uint64_t curTime = (uint64_t)BSL_SAL_CurrentSysTimeGet(); /* Check whether the validity is valid */ if (SESS_CheckValidity(sess, curTime) == false) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16707, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "sess time out", 0, 0, 0, 0); sess = NULL; } EXIT: BSL_SAL_ThreadUnlock(mgr->lock); return sess; } #endif /* HITLS_TLS_FEATURE_SESSION_ID */ /* Search for the matched session without checking the validity of the session */ bool SESSMGR_HasMacthSessionId(TLS_SessionMgr *mgr, uint8_t *sessionId, uint8_t sessionIdSize) { if (mgr == NULL || sessionId == NULL || sessionIdSize == 0) { return false; } HITLS_Session *sess = NULL; BSL_SAL_ThreadReadLock(mgr->lock); SessionKey key = {0}; key.sessionIdSize = sessionIdSize; if (memcpy_s(key.sessionId, sizeof(key.sessionId), sessionId, sessionIdSize) == EOK) { // Query the session corresponding to the key BSL_HASH_At(mgr->hash, (uintptr_t)&key, (uintptr_t *)&sess); } BSL_SAL_ThreadUnlock(mgr->lock); return (sess == NULL) ? false : true; } /* Clear timeout sessions */ void SESSMGR_ClearTimeout(TLS_SessionMgr *mgr) { if (mgr == NULL) { return; } uint64_t curTime = (uint64_t)BSL_SAL_CurrentSysTimeGet(); BSL_SAL_ThreadWriteLock(mgr->lock); BSL_HASH_Iterator it = BSL_HASH_IterBegin(mgr->hash); while (it != BSL_HASH_IterEnd(mgr->hash)) { uintptr_t ptr = BSL_HASH_IterValue(mgr->hash, it); HITLS_Session *sess = (HITLS_Session *)ptr; if (SESS_CheckValidity(sess, curTime) == false) { /* Delete the node if it is invalid */ uintptr_t tmpKey = BSL_HASH_HashIterKey(mgr->hash, it); // Returns the next iterator of the iterator where the key resides it = BSL_HASH_Erase(mgr->hash, tmpKey); } else { it = BSL_HASH_IterNext(mgr->hash, it); } } BSL_SAL_ThreadUnlock(mgr->lock); return; } int32_t SESSMGR_GernerateSessionId(TLS_Ctx *ctx, uint8_t *sessionId, uint32_t sessionIdSize) { int32_t ret = 0; int32_t retry = 0; do { ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), sessionId, sessionIdSize); if (ret != HITLS_SUCCESS) { return ret; } /* If duplicate session IDs already exist, generate new session ID */ if (SESSMGR_HasMacthSessionId(ctx->config.tlsConfig.sessMgr, sessionId, (uint8_t)sessionIdSize) == false) { return HITLS_SUCCESS; } retry++; } while (retry < SESSION_GERNERATE_RETRY_MAX_TIMES); // Maximum number of attempts is 10 BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15961, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Gernerate server session id error.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_SESSION_ID_GENRATE); return HITLS_SESS_ERR_SESSION_ID_GENRATE; } #ifdef HITLS_TLS_FEATURE_SESSION_TICKET void SESSMGR_SetTicketKeyCb(TLS_SessionMgr *mgr, HITLS_TicketKeyCb ticketKeyCb) { if (mgr != NULL) { BSL_SAL_ThreadWriteLock(mgr->lock); mgr->ticketKeyCb = ticketKeyCb; BSL_SAL_ThreadUnlock(mgr->lock); } return; } HITLS_TicketKeyCb SESSMGR_GetTicketKeyCb(TLS_SessionMgr *mgr) { if (mgr == NULL) { return NULL; } HITLS_TicketKeyCb ticketKeyCb; BSL_SAL_ThreadReadLock(mgr->lock); ticketKeyCb = mgr->ticketKeyCb; BSL_SAL_ThreadUnlock(mgr->lock); return ticketKeyCb; } int32_t SESSMGR_GetTicketKey(const TLS_SessionMgr *mgr, uint8_t *key, uint32_t keySize, uint32_t *outSize) { if (mgr == NULL || key == NULL || outSize == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16708, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } BSL_SAL_ThreadReadLock(mgr->lock); uint32_t offset = 0; if (memcpy_s(key, keySize, mgr->ticketKeyName, HITLS_TICKET_KEY_NAME_SIZE) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16709, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_SAL_ThreadUnlock(mgr->lock); return HITLS_MEMCPY_FAIL; } offset += HITLS_TICKET_KEY_NAME_SIZE; if (memcpy_s(&key[offset], keySize - offset, mgr->ticketAesKey, HITLS_TICKET_KEY_SIZE) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16710, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_SAL_ThreadUnlock(mgr->lock); return HITLS_MEMCPY_FAIL; } offset += HITLS_TICKET_KEY_SIZE; if (memcpy_s(&key[offset], keySize - offset, mgr->ticketHmacKey, HITLS_TICKET_KEY_SIZE) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16711, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_SAL_ThreadUnlock(mgr->lock); return HITLS_MEMCPY_FAIL; } offset += HITLS_TICKET_KEY_SIZE; *outSize = offset; BSL_SAL_ThreadUnlock(mgr->lock); return HITLS_SUCCESS; } int32_t SESSMGR_SetTicketKey(TLS_SessionMgr *mgr, const uint8_t *key, uint32_t keySize) { if (mgr == NULL || key == NULL || (keySize != HITLS_TICKET_KEY_NAME_SIZE + HITLS_TICKET_KEY_SIZE + HITLS_TICKET_KEY_SIZE)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16712, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } BSL_SAL_ThreadWriteLock(mgr->lock); uint32_t offset = 0; (void)memcpy_s(mgr->ticketKeyName, HITLS_TICKET_KEY_NAME_SIZE, key, HITLS_TICKET_KEY_NAME_SIZE); offset += HITLS_TICKET_KEY_NAME_SIZE; (void)memcpy_s(mgr->ticketAesKey, HITLS_TICKET_KEY_SIZE, &key[offset], HITLS_TICKET_KEY_SIZE); offset += HITLS_TICKET_KEY_SIZE; (void)memcpy_s(mgr->ticketHmacKey, HITLS_TICKET_KEY_SIZE, &key[offset], HITLS_TICKET_KEY_SIZE); BSL_SAL_ThreadUnlock(mgr->lock); return HITLS_SUCCESS; } #endif /* #ifdef HITLS_TLS_FEATURE_SESSION_TICKET */ #endif /* HITLS_TLS_FEATURE_SESSION */
2301_79861745/bench_create
tls/feature/session/src/session_mgr.c
C
unknown
15,458
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_SESSION_TICKET #include <stdbool.h> #include <string.h> #include "securec.h" #include "tlv.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "crypt.h" #include "hitls_error.h" #include "session_type.h" #include "session_enc.h" typedef struct { uint8_t keyName[HITLS_TICKET_KEY_NAME_SIZE]; uint8_t iv[HITLS_TICKET_IV_SIZE]; uint32_t encryptedStateSize; uint8_t *encryptedState; uint8_t mac[HITLS_TICKET_KEY_SIZE]; } Ticket; #define DEFAULT_SESSION_ENCRYPT_TYPE HITLS_AEAD_CIPHER #define DEFAULT_SESSION_ENCRYPT_ALGO HITLS_CIPHER_AES_256_GCM #ifdef HITLS_TLS_SUITE_CIPHER_CBC #define AES_CBC_BLOCK_LEN 16u #endif static void SetCipherInfo(const TLS_SessionMgr *sessMgr, Ticket *ticket, HITLS_CipherParameters *cipher) { cipher->type = DEFAULT_SESSION_ENCRYPT_TYPE; cipher->algo = DEFAULT_SESSION_ENCRYPT_ALGO; cipher->key = sessMgr->ticketAesKey; cipher->keyLen = HITLS_TICKET_KEY_SIZE; cipher->iv = ticket->iv; cipher->ivLen = HITLS_TICKET_IV_SIZE; cipher->aad = ticket->iv; cipher->aadLen = HITLS_TICKET_IV_SIZE; return; } static int32_t GetSessEncryptInfo(TLS_Ctx *ctx, const TLS_SessionMgr *sessMgr, Ticket *ticket, HITLS_CipherParameters *cipher) { int32_t ret; #ifdef HITLS_TLS_FEATURE_SESSION HITLS_TicketKeyCb cb = sessMgr->ticketKeyCb; if (cb != NULL) { ret = cb(ticket->keyName, HITLS_TICKET_KEY_NAME_SIZE, cipher, true); if (memcpy_s(ticket->iv, HITLS_TICKET_IV_SIZE, cipher->iv, cipher->ivLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_TICKET_KEY_RET_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16069, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "iv copy fail when GetSessEncryptInfo.", 0, 0, 0, 0); return HITLS_TICKET_KEY_RET_FAIL; } return ret; } #endif /* The user does not register the callback. The default ticket key is used. */ (void)memcpy_s(ticket->keyName, HITLS_TICKET_KEY_NAME_SIZE, sessMgr->ticketKeyName, HITLS_TICKET_KEY_NAME_SIZE); ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), ticket->iv, HITLS_TICKET_IV_SIZE); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_TICKET_KEY_RET_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16021, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Rand fail", 0, 0, 0, 0); return HITLS_TICKET_KEY_RET_FAIL; } SetCipherInfo(sessMgr, ticket, cipher); return HITLS_TICKET_KEY_RET_SUCCESS; } static int32_t PackKeyNameAndIv(const Ticket *ticket, uint8_t *data, uint32_t len, uint32_t *usedLen) { uint32_t offset = 0; if (memcpy_s(&data[0], len, ticket->keyName, HITLS_TICKET_KEY_NAME_SIZE) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16022, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy keyName fail when encrypt session ticket.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } offset += HITLS_TICKET_KEY_NAME_SIZE; if (memcpy_s(&data[offset], len - offset, ticket->iv, HITLS_TICKET_IV_SIZE) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16023, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy iv fail when encrypt session ticket.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } offset += HITLS_TICKET_IV_SIZE; *usedLen = offset; return HITLS_SUCCESS; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC static uint32_t GetCbcPendingLen(uint32_t encodeLen, uint8_t *paddingLen) { *paddingLen = (encodeLen + sizeof(uint8_t)) % AES_CBC_BLOCK_LEN; if (*paddingLen != 0) { *paddingLen = AES_CBC_BLOCK_LEN - *paddingLen; } return *paddingLen + sizeof(uint8_t); } #endif static int32_t PackEncryptTicket(HITLS_Lib_Ctx *libCtx, const char *attrName, const HITLS_Session *sess, HITLS_CipherParameters *cipher, uint8_t *data, uint32_t len, uint32_t *usedLen) { int32_t ret = 0; /* Encode the session. */ uint32_t encodeLen = SESS_GetTotalEncodeSize(sess); uint32_t plaintextLen = encodeLen; #ifdef HITLS_TLS_SUITE_CIPHER_CBC uint8_t paddingLen = 0; if (cipher->type == HITLS_CBC_CIPHER) { /* In CBC mode, the padding needs to be calculated. */ /* Plain text length plus padding length */ plaintextLen += GetCbcPendingLen(encodeLen, &paddingLen); } #endif uint8_t *plaintext = BSL_SAL_Calloc(1u, plaintextLen); if (plaintext == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16024, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encData malloc fail when encrypt session ticket.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ret = SESS_Encode(sess, plaintext, plaintextLen, &plaintextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_CleanseData(plaintext, plaintextLen); BSL_SAL_FREE(plaintext); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16025, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESS_Encode fail when encrypt session ticket.", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC /* Padding is required in CBC mode. */ if (cipher->type == HITLS_CBC_CIPHER) { /* The last byte is the padding length field, and the padding content is the length value. */ uint32_t count = paddingLen + sizeof(uint8_t); /* The calculation is accurate when the memory is applied for the plaintext. Therefore, the * return value does not need to be checked. */ (void)memset_s(&plaintext[encodeLen], count, paddingLen, count); plaintextLen += count; } #endif uint32_t offset = 0; /* reserved length field */ offset += sizeof(uint32_t); /* Encrypt and fill the ticket. */ uint32_t encryptLen = len - offset; ret = SAL_CRYPT_Encrypt(libCtx, attrName, cipher, plaintext, plaintextLen, &data[offset], &encryptLen); BSL_SAL_CleanseData(plaintext, plaintextLen); BSL_SAL_FREE(plaintext); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16026, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SAL_CRYPT_Encrypt fail when encrypt session ticket.", 0, 0, 0, 0); return ret; } /* padding length */ BSL_Uint32ToByte(encryptLen, &data[offset - sizeof(uint32_t)]); offset += encryptLen; *usedLen = offset; return HITLS_SUCCESS; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC static int32_t PackTicketHmac(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CipherParameters *cipher, uint8_t *data, uint32_t len, uint32_t offset, uint32_t *usedLen) { /* The HMAC field is filled only in CBC mode. In other modes, the HMAC field is returned. */ if (cipher->type != HITLS_CBC_CIPHER) { *usedLen = 0; return HITLS_SUCCESS; } int32_t ret; uint8_t mac[HITLS_TICKET_KEY_SIZE] = {0}; uint32_t macLen = HITLS_TICKET_KEY_SIZE; ret = SAL_CRYPT_Hmac(libCtx, attrName, HITLS_HASH_SHA_256, cipher->hmacKey, cipher->hmacKeyLen, data, offset, mac, &macLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16027, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TicketHmac fail when encrypt session ticket.", 0, 0, 0, 0); return ret; } if (memcpy_s(&data[offset], len - offset, mac, macLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16028, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy mac fail when encrypt session ticket.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } *usedLen = macLen; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_CIPHER_CBC */ static uint8_t *NewTicketBuf(const HITLS_Session *sess, HITLS_CipherParameters *cipher, uint32_t *ticketBufSize) { (void)cipher; uint32_t encodeLen = SESS_GetTotalEncodeSize(sess); uint32_t plaintextLen = encodeLen; #ifdef HITLS_TLS_SUITE_CIPHER_CBC if (cipher->type == HITLS_CBC_CIPHER) { /* In CBC mode, the padding needs to be calculated. */ uint8_t paddingLen = (encodeLen + sizeof(uint8_t)) % AES_CBC_BLOCK_LEN; if (paddingLen != 0) { paddingLen = AES_CBC_BLOCK_LEN - paddingLen; } /* Plain text length plus padding length */ plaintextLen += paddingLen + sizeof(uint8_t); } #endif /* Plain text length plus key name, iv, encrypted data length, and MAC length. */ plaintextLen += HITLS_TICKET_KEY_NAME_SIZE + HITLS_TICKET_IV_SIZE + sizeof(uint32_t) + HITLS_TICKET_KEY_SIZE; uint8_t *ticketBuf = BSL_SAL_Calloc(1u, plaintextLen); if (ticketBuf == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16029, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ticketBuf malloc fail when encrypt session ticket.", 0, 0, 0, 0); return NULL; } *ticketBufSize = plaintextLen; return ticketBuf; } int32_t SESSMGR_EncryptSessionTicket(TLS_Ctx *ctx, const TLS_SessionMgr *sessMgr, const HITLS_Session *sess, uint8_t **ticketBuf, uint32_t *ticketBufSize) { if (sessMgr == NULL || sess == NULL || ticketBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16713, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } Ticket ticket = {0}; HITLS_CipherParameters cipher = {0}; int32_t retVal = GetSessEncryptInfo(ctx, sessMgr, &ticket, &cipher); if (retVal < 0) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_SESSION_TICKET_KEY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16030, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetSessEncryptInfo fail when encrypt session ticket.", 0, 0, 0, 0); return HITLS_SESS_ERR_SESSION_TICKET_KEY_FAIL; } if (retVal == HITLS_TICKET_KEY_RET_FAIL) { /* Failed to obtain the encryption information. An empty ticket is returned. */ *ticketBufSize = 0; return HITLS_SUCCESS; } uint32_t dataLen = 0; uint8_t *data = NewTicketBuf(sess, &cipher, &dataLen); if (data == NULL) { return HITLS_MEMALLOC_FAIL; } /* Fill in the key name and iv. */ int32_t ret; uint32_t packLen = 0; uint32_t offset = 0; ret = PackKeyNameAndIv(&ticket, &data[0], dataLen, &packLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(data); return ret; } offset += packLen; /* Encrypt and fill the ticket. */ ret = PackEncryptTicket(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), sess, &cipher, &data[offset], dataLen - offset, &packLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(data); return ret; } offset += packLen; #ifdef HITLS_TLS_SUITE_CIPHER_CBC /* fill HMAC */ ret = PackTicketHmac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipher, data, dataLen, offset, &packLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(data); return ret; } offset += packLen; #endif *ticketBufSize = offset; *ticketBuf = data; return HITLS_SUCCESS; } static int32_t ParseSessionTicket(Ticket *ticket, const uint8_t *ticketBuf, uint32_t ticketBufSize) { uint32_t offset = 0; if (ticketBufSize < HITLS_TICKET_KEY_NAME_SIZE + HITLS_TICKET_IV_SIZE + sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_SESSION_TICKET_SIZE_INCORRECT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16044, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ticketBufSize is incorrect when parse session ticket.", 0, 0, 0, 0); return HITLS_SESS_ERR_SESSION_TICKET_SIZE_INCORRECT; } (void)memcpy_s(ticket->keyName, HITLS_TICKET_KEY_NAME_SIZE, ticketBuf, HITLS_TICKET_KEY_NAME_SIZE); offset += HITLS_TICKET_KEY_NAME_SIZE; (void)memcpy_s(ticket->iv, HITLS_TICKET_IV_SIZE, &ticketBuf[offset], HITLS_TICKET_IV_SIZE); offset += HITLS_TICKET_IV_SIZE; ticket->encryptedStateSize = BSL_ByteToUint32(&ticketBuf[offset]); offset += sizeof(uint32_t); if ((ticketBufSize - offset) < ticket->encryptedStateSize) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_SESSION_TICKET_SIZE_INCORRECT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16032, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ticketBufSize is incorrect when parse session ticket encryptedStateSize.", 0, 0, 0, 0); return HITLS_SESS_ERR_SESSION_TICKET_SIZE_INCORRECT; } ticket->encryptedState = (uint8_t *)(uintptr_t)&ticketBuf[offset]; offset += ticket->encryptedStateSize; if (ticketBufSize != offset) { if ((ticketBufSize - offset) != HITLS_TICKET_KEY_SIZE) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_SESSION_TICKET_SIZE_INCORRECT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16033, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ticketBufSize is incorrect when parse session ticket hmac.", 0, 0, 0, 0); return HITLS_SESS_ERR_SESSION_TICKET_SIZE_INCORRECT; } (void)memcpy_s(ticket->mac, HITLS_TICKET_KEY_SIZE, &ticketBuf[offset], HITLS_TICKET_KEY_SIZE); } return HITLS_SUCCESS; } static int32_t GetSessDecryptInfo(const TLS_SessionMgr *sessMgr, Ticket *ticket, HITLS_CipherParameters *cipher) { #ifdef HITLS_TLS_FEATURE_SESSION HITLS_TicketKeyCb cb = sessMgr->ticketKeyCb; if (cb != NULL) { return cb(ticket->keyName, HITLS_TICKET_KEY_NAME_SIZE, cipher, false); } #endif /* The user does not register the callback. Use the default ticket key. */ if (memcmp(ticket->keyName, sessMgr->ticketKeyName, HITLS_TICKET_KEY_NAME_SIZE) != 0) { /* Failed to match the key name. */ return HITLS_TICKET_KEY_RET_FAIL; } SetCipherInfo(sessMgr, ticket, cipher); return HITLS_TICKET_KEY_RET_SUCCESS; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC static int32_t CheckTicketHmac(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CipherParameters *cipher, Ticket *ticket, const uint8_t *data, uint32_t len, bool *isPass) { /* The HMAC check is required only in CBC mode. In other modes, the HMAC check is returned. */ if (cipher->type != HITLS_CBC_CIPHER) { *isPass = true; return HITLS_SUCCESS; } int32_t ret; uint8_t mac[HITLS_TICKET_KEY_SIZE] = {0}; uint32_t macLen = HITLS_TICKET_KEY_SIZE; ret = SAL_CRYPT_Hmac(libCtx, attrName, HITLS_HASH_SHA_256, cipher->hmacKey, cipher->hmacKeyLen, data, len - HITLS_TICKET_KEY_SIZE, mac, &macLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16035, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TicketHmac fail when decrypt session ticket.", 0, 0, 0, 0); return ret; } if (memcmp(ticket->mac, mac, macLen) != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16036, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "compare mac fail when decrypt session ticket.", 0, 0, 0, 0); /* The HMAC check fails, but the complete link establishment can be continued. Therefore, HITLS_SUCCESS is * returned. */ *isPass = false; return HITLS_SUCCESS; } *isPass = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_CIPHER_CBC */ static int32_t GenerateSessFromTicket(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CipherParameters *cipher, Ticket *ticket, uint32_t ticketBufSize, HITLS_Session **sess) { /* Decrypt the ticket. */ uint32_t plaintextLen = ticketBufSize; uint8_t *plaintext = BSL_SAL_Calloc(1u, ticketBufSize); if (plaintext == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16037, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "plaintext malloc fail when decrypt session ticket.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } int32_t ret; ret = SAL_CRYPT_Decrypt(libCtx, attrName, cipher, ticket->encryptedState, ticket->encryptedStateSize, plaintext, &plaintextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(plaintext); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16038, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "SAL_CRYPT_Decrypt fail when decrypt session ticket.", 0, 0, 0, 0); /* The ticket fails to be decrypted, but the complete connection can be established. Therefore, HITLS_SUCCESS is * returned. */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC /* Padding needs to be verified in CBC mode. */ if (cipher->type == HITLS_CBC_CIPHER) { /* The last byte is the padding length field, and the padding content is the length value. */ uint8_t paddingLen = plaintext[plaintextLen - 1]; for (uint32_t i = 1; i <= paddingLen; i++) { if (plaintext[plaintextLen - 1 - i] != paddingLen) { BSL_SAL_FREE(plaintext); return HITLS_SUCCESS; } } plaintextLen -= paddingLen + sizeof(uint8_t); } #endif /* Parse the ticket content to the SESS. */ HITLS_Session *session = HITLS_SESS_New(); if (session == NULL) { BSL_SAL_FREE(plaintext); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16039, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HITLS_SESS_New fail when decrypt session ticket.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ret = SESS_Decode(session, plaintext, plaintextLen); BSL_SAL_FREE(plaintext); if (ret != HITLS_SUCCESS) { HITLS_SESS_Free(session); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16040, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "SESS_Decode fail when decrypt session ticket.", 0, 0, 0, 0); /* The ticket content fails to be parsed, but the complete connection can be established. Therefore, * HITLS_SUCCESS is returned. */ return HITLS_SUCCESS; } *sess = session; return HITLS_SUCCESS; } 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 *isTicketExpect) { if (sessMgr == NULL || sess == NULL || ticketBuf == NULL || isTicketExpect == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16041, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESSMGR_DecryptSessionTicket input parameter is NULL.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } int32_t ret; Ticket ticket = {0}; /* Parse the data into the ticket structure. */ ret = ParseSessionTicket(&ticket, ticketBuf, ticketBufSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16042, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "ParseSessionTicket fail when decrypt session ticket.", 0, 0, 0, 0); /* If the ticket fails to be parsed, the session is not resumption and the complete connection is established. * Therefore, HITLS_SUCCESS is returned. */ *isTicketExpect = true; return HITLS_SUCCESS; } /* Obtain decryption information. */ HITLS_CipherParameters cipher = {0}; int32_t retVal = GetSessDecryptInfo(sessMgr, &ticket, &cipher); if (retVal < 0) { BSL_ERR_PUSH_ERROR(HITLS_SESS_ERR_SESSION_TICKET_KEY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16043, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetSessDecryptInfo fail when decrypt session ticket.", 0, 0, 0, 0); return HITLS_SESS_ERR_SESSION_TICKET_KEY_FAIL; } switch (retVal) { case HITLS_TICKET_KEY_RET_FAIL: /* If no corresponding key is found, the system directly returns a message and complete link establishment * is performed. */ *isTicketExpect = true; return HITLS_SUCCESS; case HITLS_TICKET_KEY_RET_SUCCESS_RENEW: *isTicketExpect = true; break; case HITLS_TICKET_KEY_RET_SUCCESS: default: *isTicketExpect = false; break; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC /* Verify the MAC address. */ bool isPass = true; ret = CheckTicketHmac(libCtx, attrName, &cipher, &ticket, ticketBuf, ticketBufSize, &isPass); if ((ret != HITLS_SUCCESS) || (!isPass)) { /* If the HMAC check fails, the session is not restored and complete link establishment is performed. */ return ret; } #endif /* Parse the ticket content to the SESS. */ return GenerateSessFromTicket(libCtx, attrName, &cipher, &ticket, ticketBufSize, sess); } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */
2301_79861745/bench_create
tls/feature/session/src/session_ticket.c
C
unknown
21,311
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_TYPE_H #define SESSION_TYPE_H #include <stdbool.h> #include <stdint.h> #include "hitls_type.h" #include "hitls_session.h" #include "tls_config.h" #include "cert.h" #include "session.h" #ifdef __cplusplus extern "C" { #endif struct TlsSessionManager { void *lock; /* Thread lock */ int32_t references; /* Reference times */ void *hash; /* hash table */ uint64_t sessTimeout; /* Session timeout interval, in seconds */ #ifdef HITLS_TLS_FEATURE_SESSION uint32_t sessCacheSize; /* session cache size: maximum number of sessions */ HITLS_SESS_CACHE_MODE sessCacheMode; /* session cache mode */ /* TLS1.2 session ticket */ HITLS_TicketKeyCb ticketKeyCb; /* allows users to customize ticket keys through callback */ #endif /* key_name: is used to identify a specific set of keys used to protect tickets */ uint8_t ticketKeyName[HITLS_TICKET_KEY_NAME_SIZE]; uint8_t ticketAesKey[HITLS_TICKET_KEY_SIZE]; /* aes key */ uint8_t ticketHmacKey[HITLS_TICKET_KEY_SIZE]; /* hmac key */ }; struct TlsSessCtx { void *lock; /* Thread lock */ /* certificate management context. The certificate interface depends on this field */ CERT_MgrCtx *certMgrCtx; int32_t references; /* Reference times */ bool enable; /* Whether to enable the session */ bool haveExtMasterSecret; /* Whether an extended master key exists */ bool reserved[2]; /* Four-byte alignment */ uint64_t startTime; /* Start time */ uint64_t timeout; /* Timeout interval */ #ifdef HITLS_TLS_FEATURE_SNI uint32_t hostNameSize; /* Length of the host name */ uint8_t *hostName; /* Host name */ #endif uint32_t sessionIdCtxSize; /* Session ID Context Length */ uint8_t sessionIdCtx[HITLS_SESSION_ID_CTX_MAX_SIZE]; /* Session ID Context */ uint32_t sessionIdSize; /* Session ID length */ uint8_t sessionId[HITLS_SESSION_ID_MAX_SIZE]; /* session ID */ int32_t verifyResult; /* Authentication result */ CERT_Pair *peerCert; /* Peer certificate */ uint16_t version; /* Version */ uint16_t cipherSuite; /* Cipher suite */ uint32_t masterKeySize; /* length of the master key */ uint8_t masterKey[MAX_MASTER_KEY_SIZE]; /* Master Key */ uint32_t ticketSize; /* Session ticket length */ uint8_t *ticket; /* Session ticket */ uint32_t ticketLifetime; /* Timeout interval of the ticket */ uint32_t ticketAgeAdd; /* A random number generated each time a ticket is issued */ void *userData; }; #define LIBCTX_FROM_SESSION_CTX(sessCtx) (sessCtx == NULL) ? NULL : ((sessCtx)->certMgrCtx == NULL ? NULL : (sessCtx)->certMgrCtx->libCtx) #define ATTRIBUTE_FROM_SESSION_CTX(sessCtx) (sessCtx == NULL) ? NULL : ((sessCtx)->certMgrCtx == NULL ? NULL : (sessCtx)->certMgrCtx->attrName) #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
tls/feature/session/src/session_type.h
C
unknown
4,274
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_SNI #include <ctype.h> #include <stdint.h> #include <string.h> #include "securec.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls_sni.h" #include "session.h" #include "tls_binlog_id.h" #include "tls.h" #include "hs.h" #include "sni.h" const char *HITLS_GetServerName(const HITLS_Ctx *ctx, const int type) { if (ctx == NULL || type != HITLS_SNI_HOSTNAME_TYPE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16756, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return NULL; } bool isClient = ctx->isClient; bool isResume = ctx->negotiatedInfo.isResume; uint16_t version = ctx->config.tlsConfig.maxVersion; uint8_t *hostName = NULL; uint32_t nameSize = 0u; SESS_GetHostName(ctx->session, &nameSize, &hostName); if (!isClient) { /* Before Handshake */ if (ctx->state == CM_STATE_IDLE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16757, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ctx->state is CM_STATE_IDLE", 0, 0, 0, 0); return NULL; } /* During or after handshake */ /* TLS protocol version < TLS1.3 session resumption */ if ((version < HITLS_VERSION_TLS13 || version == HITLS_VERSION_DTLS12) && isResume && ctx->session != NULL) { return (char *)hostName; } } else { /* Before Handshake */ if (ctx->state == CM_STATE_IDLE) { /* resume the session */ if (ctx->config.tlsConfig.serverName == NULL && ctx->session != NULL && (version < HITLS_VERSION_TLS13 || version == HITLS_VERSION_DTLS12)) { return (char *)hostName; } /* resume non-session */ return (char *)ctx->config.tlsConfig.serverName; } else { /* During or after handshake */ /* resume the session */ if (ctx->session != NULL && (version < HITLS_VERSION_TLS13 || version == HITLS_VERSION_DTLS12)) { return (char *)hostName; } /* resume non-session */ return (char *)ctx->config.tlsConfig.serverName; } } return HS_GetServerName(ctx); } int32_t HITLS_GetServernameType(const HITLS_Ctx *ctx) { int32_t ret = -1; if (HITLS_GetServerName(ctx, HITLS_SNI_HOSTNAME_TYPE) != NULL) { return HITLS_SNI_HOSTNAME_TYPE; } return ret; } /* Check whether the host names are the same */ int32_t SNI_StrcaseCmp(const char *s1, const char *s2) { int32_t ret = -1; if (s1 == NULL && s2 == NULL) { return 0; } if (s1 == NULL || s2 == NULL) { return ret; } const char *a = s1; const char *b = s2; int32_t len1 = (int32_t)strlen(s1); int32_t len2 = (int32_t)strlen(s2); if (len1 != len2) { return ret; } while (tolower((int32_t)*a) == tolower((int32_t)*b)) { if (*a == '\0') { return 0; } a++; b++; } return ret; } #endif /* HITLS_TLS_FEATURE_SNI */
2301_79861745/bench_create
tls/feature/sni/src/sni.c
C
unknown
3,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. */ #ifndef HS_COMMON_H #define HS_COMMON_H #include <stdint.h> #include "tls.h" #include "hs_ctx.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif #define MAX_CERT_TYPE_LISTS_SIZE 256 /* Maximum length of the certificate type list */ #define HS_DOWNGRADE_RANDOM_SIZE 8u /* downgrade protection random number field */ #define HITLS_CLIENT_HELLO_MAX_SIZE 131396 #define HITLS_SERVER_HELLO_MAX_SIZE 65607 #define HITLS_HELLO_VERIFY_REQUEST_MAX_SIZE 258 #define HITLS_END_OF_EARLY_DATA_MAX_SIZE 0 #define HITLS_HELLO_RETRY_REQUEST_MAX_SIZE 20000 #define HITLS_ENCRYPTED_EXTENSIONS_MAX_SIZE 20000 #define HITLS_SESSION_TICKET_MAX_SIZE_TLS13 131338 #define HITLS_SESSION_TICKET_MAX_SIZE_TLS12 65541 #define HITLS_SERVER_KEY_EXCH_MAX_SIZE 102400 #define HITLS_SERVER_HELLO_DONE_MAX_SIZE 0 #define HITLS_KEY_UPDATE_MAX_SIZE 1 #define HITLS_CLIENT_KEY_EXCH_MAX_SIZE 2048 #define HITLS_NEXT_PROTO_MAX_SIZE 514 #define HITLS_FINISHED_MAX_SIZE 64 #define HITLS_HELLO_REQUEST_MAX_SIZE 0 /** * @brief Obtain the random number of the hello retry request. * * @param len [OUT] Length of the returned array * * @return Random number array */ const uint8_t *HS_GetHrrRandom(uint32_t *len); const uint8_t *HS_GetTls12DowngradeRandom(uint32_t *len); /** * @brief Obtains the type string of the handshake message. * * @param type [IN] Handshake Message Type * * @return Character string corresponding to the handshake message type. */ const char *HS_GetMsgTypeStr(HS_MsgType type); /** * @brief Obtain the type character string of the handshake message. * * @param type [IN] Handshake message type. * * @return Character string corresponding to the handshake message type. */ int32_t HS_ChangeState(TLS_Ctx *ctx, uint32_t nextState); /** * @brief Combine two random numbers. * * @param random1 [IN] Random number 1 * @param random2 [IN] Random number 2 * @param randomSize [IN] Random number length * @param dest [OUT] Destination memory address * @param destSize [IN] Target memory length * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_MEMCPY_FAIL Memory Copy Failure * @retval HITLS_MSG_HANDLE_RANDOM_SIZE_ERR The random number length is incorrect. */ int32_t HS_CombineRandom(const uint8_t *random1, const uint8_t *random2, uint32_t randomSize, uint8_t *dest, uint32_t destSize); /** * @brief Obtain all signature data. * * @param ctx [IN] TLS context * @param partSignData [IN] key exchange message data * @param partSignDataLen [IN] key exchange message data length * @param signDataLen [OUT] Length of the signature data * * @retval Data to be signed */ uint8_t *HS_PrepareSignData(const TLS_Ctx *ctx, const uint8_t *partSignData, uint32_t partSignDataLen, uint32_t *signDataLen); /** * @brief Obtain the signature data required by the TLCP. * * @param ctx [IN] TLS context * @param partSignData [IN] key exchange message data * @param partSignDataLen [IN] key exchange message data length * @param signDataLen [OUT] Length of the signature data * @retval Data to be signed */ uint8_t *HS_PrepareSignDataTlcp( const TLS_Ctx *ctx, const uint8_t *partSignData, uint32_t partSignDataLen, uint32_t *signDataLen); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) /** * @brief Set the SCTP auth key to the SCTP. * * @attention If the UIO_SctpAddAuthKey is added but not activated, the UIO_SctpAddAuthKey returns a success message * when the interface is invoked again. * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS Operation succeeded. * @retval HITLS_MSG_HANDLE_RANDOM_SIZE_ERR The random number length is incorrect. * @retval For details, see UIO_SctpAddAuthKey. */ int32_t HS_SetSctpAuthKey(TLS_Ctx *ctx); /** * @brief Activate the sctp auth key. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS operation succeeded. * @retval For details, see UIO_SctpIsSndBuffEmpty and UIO_SctpActiveAuthKey. */ int32_t HS_ActiveSctpAuthKey(TLS_Ctx *ctx); /** * @brief Delete the previous SCTP auth key. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS Operation succeeded. * @retval HITLS_REC_NORMAL_IO_BUSY The underlying I/O buffer is not empty. * @retval For details, see UIO_SctpDelPreAuthKey. */ int32_t HS_DeletePreviousSctpAuthKey(TLS_Ctx *ctx); #endif /* #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) */ bool IsNeedServerKeyExchange(const TLS_Ctx *ctx); bool IsPskNegotiation(const TLS_Ctx *ctx); bool IsNeedCertPrepare(const CipherSuiteInfo *cipherSuiteInfo); bool IsTicketSupport(const TLS_Ctx *ctx); int32_t CheckClientPsk(TLS_Ctx *ctx); /** * @brief Expand the capacity of the msgBuf in the hsCtx based on the received message length. * * @param ctx [IN] TLS context * @param msgSize[IN] Expected length * * @retval HITLS_SUCCESS Operation succeeded. * @retval HITLS_MEMALLOC_FAIL failed to apply for memory. */ int32_t HS_ReSizeMsgBuf(TLS_Ctx *ctx, uint32_t msgSize); /** * @brief Expand the capacity of the msgBuf in the hsCtx based on the length of the received message. The upper limit of * the capacity does not exceed upperBound bytes, And you can choose whether to retain the original data * @param ctx [IN] TLS context * @param msgSize[IN] Expected length * @param keepOldData[IN] Indicates whether to retain the old data. * * @retval HITLS_SUCCESS Operation succeeded. * @retval HITLS_MEMALLOC_FAIL failed to apply for memory. * @retval HITLS_MEMCPY_FAIL Data fails to be copied. */ int32_t HS_GrowMsgBuf(TLS_Ctx *ctx, uint32_t msgSize, bool keepOldData); /** * @brief Return the maximum packet length allowed by the handshake status. * * @param ctx [IN] TLS context * @param type[IN] Handshake message type * * @retval Maximum message length allowed */ uint32_t HS_MaxMessageSize(TLS_Ctx *ctx, HS_MsgType type); /** * @brief Obtain the Binder length. * * @param ctx [IN] TLS context * @param hashAlg [IN/OUT] Hash algorithm used in the process of calculating the binder * * @return Binder length */ uint32_t HS_GetBinderLen(HITLS_Session *session, HITLS_HashAlgo* hashAlg); /** * @brief Check whether the current version supports this group. * * @param version [IN] current version * @param group [IN] group * * @return true: valid; false: invalid */ bool GroupConformToVersion(const TLS_Ctx *ctx, uint16_t version, uint16_t group); /** * @brief Check whether the ciphersuite is valid * * @param ctx [IN] TLS context * @param cipherSuite [IN] cipherSuite * * @return true: valid; false: invalid */ bool IsCipherSuiteAllowed(const HITLS_Ctx *ctx, uint16_t cipherSuite); uint16_t *CheckSupportSignAlgorithms(const TLS_Ctx *ctx, const uint16_t *signAlgorithms, uint32_t signAlgorithmsSize, uint32_t *newSignAlgorithmsSize); uint32_t HS_GetExtensionTypeId(uint32_t hsExtensionsType); int32_t HS_CheckReceivedExtension(HITLS_Ctx *ctx, HS_MsgType hsType, uint64_t hsMsgExtensionsMask, uint64_t hsMsgAllowedExtensionsMask); #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
tls/handshake/common/include/hs_common.h
C
unknown
7,642
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_CTX_H #define HS_CTX_H #include <stdint.h> #include "hitls_build.h" #include "sal_time.h" #include "hitls_cert_type.h" #include "hitls_crypt_type.h" #include "cert.h" #include "crypt.h" #include "rec.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif #define MASTER_SECRET_LEN 48u #define HS_PSK_IDENTITY_MAX_LEN 128u /* Maximum length of PSK-negotiated identity information */ #define HS_PSK_MAX_LEN 256u #define COOKIE_SECRET_LIFETIME 5u /* the number of times the cookie's secret is used */ #ifndef HITLS_HS_INIT_BUFFER_SIZE #define HITLS_HS_INIT_BUFFER_SIZE 4096u #endif #ifndef HITLS_HS_BUFFER_SIZE_LIMIT #define HITLS_HS_BUFFER_SIZE_LIMIT 20480u #endif #if HITLS_HS_INIT_BUFFER_SIZE < 32 #error "HITLS_HS_INIT_BUFFER_SIZE must be greater than or equal to 32" #endif #if HITLS_HS_BUFFER_SIZE_LIMIT < HITLS_HS_INIT_BUFFER_SIZE #error "HITLS_HS_BUFFER_SIZE_LIMIT must be greater than or equal to HITLS_HS_INIT_BUFFER_SIZE" #endif #define UINT24_SIZE 3u /* Transmits ECDH key exchange data */ typedef struct { HITLS_ECParameters curveParams; /* Elliptic curve parameter */ } EcdhParam; /* Transmits DH key exchange data */ typedef struct { uint8_t *p; /* prime */ uint8_t *g; /* generator */ uint16_t plen; /* prime length */ uint16_t glen; /* generator length */ } DhParam; /* Used to transfer RSA key exchange data */ typedef struct { uint8_t preMasterSecret[MASTER_SECRET_LEN]; } RsaParam; /* Used to transfer Ecc key exchange data */ typedef struct { uint8_t preMasterSecret[MASTER_SECRET_LEN]; } EccParam; typedef struct { /* For TLS1.3 multi-key share, we try to send two key shares: * - One for key encapsulation mechanism (KEM) * - One for key exchange (KEX) */ HITLS_NamedGroup group; /* First group for key share */ HITLS_NamedGroup secondGroup; /* Second group for key share */ } KeyShareParam; /** * @ingroup hitls * * @brief PskInfo is used for PSK negotiation and stores identity and psk during negotiation */ #ifdef HITLS_TLS_FEATURE_PSK typedef struct { uint8_t *identity; uint32_t identityLen; uint8_t *psk; uint32_t pskLen; } PskInfo; #endif /* HITLS_TLS_FEATURE_PSK */ #ifdef HITLS_TLS_PROTO_TLS13 typedef struct { uint8_t *identity; uint32_t identityLen; HITLS_Session *pskSession; uint8_t num; } UserPskList; typedef struct { UserPskList *userPskSess; /* tls 1.3 user psk session */ HITLS_Session *resumeSession; /* tls 1.3 psk resume */ int32_t selectIndex; /* selected index */ uint8_t *psk; /* selected psk */ uint32_t pskLen; } PskInfo13; #endif /* HITLS_TLS_PROTO_TLS13 */ /* Used to transfer the key exchange context */ typedef struct { HITLS_KeyExchAlgo keyExchAlgo; union { EcdhParam ecdh; DhParam dh; RsaParam rsa; EccParam ecc; /* Sm2 parameter */ KeyShareParam share; } keyExchParam; HITLS_CRYPT_Key *key; /* Local key pair */ HITLS_CRYPT_Key *secondKey; /* second key pair for tls1.3 multi-key share */ uint8_t *peerPubkey; /* peer public key or peer ciphertext */ uint32_t pubKeyLen; /* peer public key length */ #ifdef HITLS_TLS_FEATURE_PSK PskInfo *pskInfo; /* PSK data tls 1.2 */ #endif /* HITLS_TLS_FEATURE_PSK */ #ifdef HITLS_TLS_PROTO_TLS13 PskInfo13 pskInfo13; /* tls 1.3 psk */ uint8_t *ciphertext; /* local ciphertext */ uint32_t ciphertextLen; /* ciphertext length */ #endif /* HITLS_TLS_PROTO_TLS13 */ } KeyExchCtx; /* Buffer for transmitting handshake data. */ typedef struct HsMsgCache { uint8_t *data; uint32_t dataSize; struct HsMsgCache *next; } HsMsgCache; /* Used to transfer the handshake data verification context. */ typedef struct { HITLS_HashAlgo hashAlgo; HITLS_HASH_Ctx *hashCtx; uint8_t verifyData[MAX_SIGN_SIZE]; uint32_t verifyDataSize; HsMsgCache *dataBuf; /* handshake data buffer */ } VerifyCtx; /* Used to pass the handshake context */ struct HsCtx { HITLS_HandshakeState state; HitlsProcessState readSubState; HS_Msg *hsMsg; ExtensionFlag extFlag; #ifdef HITLS_TLS_PROTO_TLS13 HITLS_HandshakeState ccsNextState; bool haveHrr; /* Whether the hello retry request has been processed */ #endif bool isNeedClientCert; #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_PROTO_TLS13) uint32_t sessionIdSize; uint8_t *sessionId; #endif uint8_t *clientRandom; uint8_t *serverRandom; #ifdef HITLS_TLS_PROTO_TLS13 uint8_t earlySecret[MAX_DIGEST_SIZE]; uint8_t handshakeSecret[MAX_DIGEST_SIZE]; #endif uint8_t masterKey[MAX_DIGEST_SIZE]; CERT_Pair *peerCert; #ifdef HITLS_TLS_FEATURE_ALPN uint8_t *clientAlpnList; uint32_t clientAlpnListSize; #endif #ifdef HITLS_TLS_FEATURE_SNI uint8_t *serverName; uint32_t serverNameSize; #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET uint32_t ticketSize; uint8_t *ticket; uint32_t ticketLifetimeHint; /* ticket timeout interval, in seconds */ #ifdef HITLS_TLS_PROTO_TLS13 uint32_t ticketAgeAdd; /* Used to obfuscate ticket age */ uint64_t nextTicketNonce; /* TLS1.3 connection, starting from 0 and increasing in ascending order */ uint32_t sentTickets; /* TLS1.3 Number of tickets sent */ #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ KeyExchCtx *kxCtx; /* Key Exchange Context */ VerifyCtx *verifyCtx; /* Verify the context of handshake data. */ uint8_t *msgBuf; /* Buffer for receiving and sending messages */ uint32_t msgOffset; /* messages offset */ uint32_t bufferLen; /* messages buffer size */ uint32_t msgLen; /* Total length of buffered messages */ #ifdef HITLS_TLS_PROTO_TLS13 uint8_t clientHsTrafficSecret[MAX_DIGEST_SIZE]; /* Handshake secret used to encrypt the message sent by the TLS1.3 client */ uint8_t serverHsTrafficSecret[MAX_DIGEST_SIZE]; /* Handshake secret used to encrypt the message sent by the TLS1.3 server */ ClientHelloMsg *firstClientHello; /* TLS1.3 server records the first received ClientHello message */ #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_DTLS12 uint16_t nextSendSeq; /* message sending sequence number */ uint16_t expectRecvSeq; /* message receiving sequence number */ HS_ReassQueue *reassMsg; /* reassembly message queue, used for reassembly of fragmented messages */ #ifdef HITLS_BSL_UIO_UDP /* To reduce the calculation amount for determining timeout, use the end time instead of the start time. If the end * time is exceeded, the receiving times out. */ BSL_TIME deadline; /* End time */ uint32_t timeoutValue; /* Timeout interval, in us. */ uint32_t timeoutNum; /* Timeout count */ #endif /* HITLS_BSL_UIO_UDP */ #endif /* HITLS_TLS_PROTO_DTLS12 */ }; #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_CTX_H */
2301_79861745/bench_create
tls/handshake/common/include/hs_ctx.h
C
unknown
7,611
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_DTLS_TIMER_H #define HS_DTLS_TIMER_H #include <stdint.h> #include <stdbool.h> #include "hs_ctx.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Start the 2MSL timer. * * @param ctx [IN] tls Context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_SYS_TIME_FAIL The system time function fails to return. */ int32_t HS_Start2MslTimer(TLS_Ctx *ctx); /** * @brief Start the timer. * * @param ctx [IN] tls Context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_SYS_TIME_FAIL The system time function fails to return. */ int32_t HS_StartTimer(TLS_Ctx *ctx); /** * @brief Judge timer timeout * * @param ctx [IN] tls Context * @param isTimeout [OUT] Timeout or not * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_SYS_TIME_FAIL The system time function fails to return. */ int32_t HS_IsTimeout(TLS_Ctx *ctx, bool *isTimeout); /** * @brief DTLS receiving timeout timer processing * * @param ctx [IN] tls Context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_SYS_TIME_FAIL The system time function fails to return. * @retval HITLS_MSG_HANDLE_DTLS_CONNECT_TIMEOUT DTLS connection timeout */ int32_t HS_TimeoutProcess(TLS_Ctx *ctx); #endif #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_DTLS_TIMER_H */
2301_79861745/bench_create
tls/handshake/common/include/hs_dtls_timer.h
C
unknown
1,912
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_EXTERNSIONS_H #define HS_EXTERNSIONS_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define HS_EX_HEADER_LEN 4u /* Handshake Extension message type */ #define HS_EX_TYPE_SERVER_NAME 0u #define HS_EX_TYPE_MAX_FRAGMENT_LENGTH 1u #define HS_EX_TYPE_TRUSTED_CA_KEYS 3u #define HS_EX_TYPE_STATUS_REQUEST 5u #define HS_EX_TYPE_SUPPORTED_GROUPS 10u #define HS_EX_TYPE_POINT_FORMATS 11u #define HS_EX_TYPE_SIGNATURE_ALGORITHMS 13u #define HS_EX_TYPE_USE_SRTP 14u #define HS_EX_TYPE_APP_LAYER_PROTOCOLS 16u #define HS_EX_TYPE_STATUS_REQUEST_V2 17u #define HS_EX_TYPE_SIGNED_CERTIFICATE_TIMESTAMP 18u #define HS_EX_TYPE_PADDING 21u #define HS_EX_TYPE_ENCRYPT_THEN_MAC 22u #define HS_EX_TYPE_EXTENDED_MASTER_SECRET 23u #define HS_EX_TYPE_RECORD_SIZE_LIMIT 28u #define HS_EX_TYPE_SESSION_TICKET 35u #define HS_EX_TYPE_PRE_SHARED_KEY 41u #define HS_EX_TYPE_EARLY_DATA 42u #define HS_EX_TYPE_SUPPORTED_VERSIONS 43u #define HS_EX_TYPE_COOKIE 44u #define HS_EX_TYPE_PSK_KEY_EXCHANGE_MODES 45u #define HS_EX_TYPE_CERTIFICATE_AUTHORITIES 47u #define HS_EX_TYPE_POST_HS_AUTH 49u #define HS_EX_TYPE_SIGNATURE_ALGORITHMS_CERT 50u #define HS_EX_TYPE_KEY_SHARE 51u #define HS_EX_TYPE_RENEGOTIATION_INFO 0xFF01u #define HS_EX_TYPE_END 0xFFFFu #define HS_EX_TYPE_ID_UNRECOGNIZED 0 #define HS_EX_TYPE_ID_SERVER_NAME 1 #define HS_EX_TYPE_ID_MAX_FRAGMENT_LENGTH 2 #define HS_EX_TYPE_ID_TRUSTED_CA_KEYS 3 #define HS_EX_TYPE_ID_STATUS_REQUEST 4 #define HS_EX_TYPE_ID_SUPPORTED_GROUPS 5 #define HS_EX_TYPE_ID_POINT_FORMATS 6 #define HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS 7 #define HS_EX_TYPE_ID_USE_SRTP 8 #define HS_EX_TYPE_ID_APP_LAYER_PROTOCOLS 9 #define HS_EX_TYPE_ID_STATUS_REQUEST_V2 10 #define HS_EX_TYPE_ID_SIGNED_CERTIFICATE_TIMESTAMP 11 #define HS_EX_TYPE_ID_PADDING 12 #define HS_EX_TYPE_ID_ENCRYPT_THEN_MAC 13 #define HS_EX_TYPE_ID_EXTENDED_MASTER_SECRET 14 #define HS_EX_TYPE_ID_RECORD_SIZE_LIMIT 15 #define HS_EX_TYPE_ID_SESSION_TICKET 16 #define HS_EX_TYPE_ID_PRE_SHARED_KEY 17 #define HS_EX_TYPE_ID_EARLY_DATA 18 #define HS_EX_TYPE_ID_SUPPORTED_VERSIONS 19 #define HS_EX_TYPE_ID_COOKIE 20 #define HS_EX_TYPE_ID_PSK_KEY_EXCHANGE_MODES 21 #define HS_EX_TYPE_ID_CERTIFICATE_AUTHORITIES 22 #define HS_EX_TYPE_ID_OID_FILTERS 23 #define HS_EX_TYPE_ID_POST_HS_AUTH 24 #define HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS_CERT 25 #define HS_EX_TYPE_ID_KEY_SHARE 26 #define HS_EX_TYPE_ID_RENEGOTIATION_INFO 27 #define HS_EX_TYPE_MASK(id) (1ULL << (id)) #define HS_EX_TYPE_TLS_ALLOWED_OF_CLIENT_HELLO \ (HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SERVER_NAME) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_MAX_FRAGMENT_LENGTH) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SUPPORTED_GROUPS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SESSION_TICKET) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_STATUS_REQUEST) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_APP_LAYER_PROTOCOLS) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_USE_SRTP) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_ENCRYPT_THEN_MAC) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNED_CERTIFICATE_TIMESTAMP) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_EXTENDED_MASTER_SECRET) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS_CERT) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_POST_HS_AUTH) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SUPPORTED_VERSIONS) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_PSK_KEY_EXCHANGE_MODES) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_KEY_SHARE) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_EARLY_DATA) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_CERTIFICATE_AUTHORITIES) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_PADDING) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_PRE_SHARED_KEY) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_RECORD_SIZE_LIMIT) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_RENEGOTIATION_INFO) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_POINT_FORMATS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_COOKIE) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_UNRECOGNIZED)) #define HS_EX_TYPE_TLS1_3_ALLOWED_OF_ENCRYPTED_EXTENSIONS \ (HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SERVER_NAME) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_MAX_FRAGMENT_LENGTH) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SUPPORTED_GROUPS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_APP_LAYER_PROTOCOLS) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_USE_SRTP) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_EARLY_DATA) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_RECORD_SIZE_LIMIT)) #define HS_EX_TYPE_TLS1_3_ALLOWED_OF_HELLO_RETRY_REQUEST \ (HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SUPPORTED_VERSIONS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_KEY_SHARE) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_COOKIE)) #define HS_EX_TYPE_TLS1_3_ALLOWED_OF_SERVER_HELLO \ (HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SUPPORTED_VERSIONS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_KEY_SHARE) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_PRE_SHARED_KEY)) #define HS_EX_TYPE_TLS1_3_ALLOWED_OF_CERTIFICATE_REQUEST \ (HS_EX_TYPE_MASK(HS_EX_TYPE_ID_STATUS_REQUEST) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNED_CERTIFICATE_TIMESTAMP) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS_CERT) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_OID_FILTERS) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_CERTIFICATE_AUTHORITIES) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_UNRECOGNIZED)) #define HS_EX_TYPE_TLS1_3_ALLOWED_OF_CERTIFICATE (HS_EX_TYPE_MASK(HS_EX_TYPE_ID_STATUS_REQUEST) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNED_CERTIFICATE_TIMESTAMP)) #define HS_EX_TYPE_TLS1_2_ALLOWED_OF_SERVER_HELLO \ (HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SERVER_NAME) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_MAX_FRAGMENT_LENGTH) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SUPPORTED_GROUPS) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_APP_LAYER_PROTOCOLS) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_STATUS_REQUEST) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SESSION_TICKET) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_USE_SRTP) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_ENCRYPT_THEN_MAC) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_SIGNED_CERTIFICATE_TIMESTAMP) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_POINT_FORMATS) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_EXTENDED_MASTER_SECRET) | HS_EX_TYPE_MASK(HS_EX_TYPE_ID_RECORD_SIZE_LIMIT) | \ HS_EX_TYPE_MASK(HS_EX_TYPE_ID_RENEGOTIATION_INFO)) #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_EXTERNSIONS_H */
2301_79861745/bench_create
tls/handshake/common/include/hs_extensions.h
C
unknown
7,412
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HS_KX_H #define HS_KX_H #include <stdint.h> #include "hs_ctx.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif #define MASTER_SECRET_LABEL "CLIENT_RANDOM" #define CLIENT_EARLY_LABEL "CLIENT_EARLY_TRAFFIC_SECRET" #define CLIENT_HANDSHAKE_LABEL "CLIENT_HANDSHAKE_TRAFFIC_SECRET" #define SERVER_HANDSHAKE_LABEL "SERVER_HANDSHAKE_TRAFFIC_SECRET" #define CLIENT_APPLICATION_LABEL "CLIENT_TRAFFIC_SECRET_0" #define SERVER_APPLICATION_LABEL "SERVER_TRAFFIC_SECRET_0" #define EARLY_EXPORTER_SECRET_LABEL "EARLY_EXPORTER_SECRET" #define EXPORTER_SECRET_LABEL "EXPORTER_SECRET" /* The maximum premaster secret calculated by using the PSK may be: * |uint16_t|MAX_OTHER_SECRET_SIZE|uint16_t|HS_PSK_MAX_LEN| */ #define MAX_OTHER_SECRET_SIZE 1536 #define MAX_PRE_MASTER_SECRET_SIZE (sizeof(uint16_t) + MAX_OTHER_SECRET_SIZE + sizeof(uint16_t) + HS_PSK_MAX_LEN) #define MAX_SHA1_SIZE 20 #define MAX_MD5_SIZE 16 /** * @brief Create a key exchange context. * * @return A KeyExchCtx pointer is returned. If NULL is returned, the creation fails. */ KeyExchCtx *HS_KeyExchCtxNew(void); /** * @brief Release the key exchange context * * @param keyExchCtx [IN] Key exchange context. KeyExchCtx is left empty by the invoker */ void HS_KeyExchCtxFree(KeyExchCtx *keyExchCtx); /** * @brief Process the server ECDHE key exchange message * * @param ctx [IN] TLS context * @param serverKxMsg [IN] Parsed handshake message * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_MSG_HANDLE_UNKNOWN_CURVE_TYPE Unsupported elliptic curve type * @retval HITLS_MSG_HANDLE_UNSUPPORT_NAMED_CURVE Unsupported ECDH elliptic curve * @retval HITLS_MSG_HANDLE_ERR_ENCODE_ECDH_KEY Failed to obtain the ECDH public key. */ int32_t HS_ProcessServerKxMsgEcdhe(TLS_Ctx *ctx, const ServerKeyExchangeMsg *serverKxMsg); /** * @brief Process the client ECDHE key exchange message * * @param ctx [IN] TLS context * @param clientKxMsg [IN] Parsed handshake message * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_MSG_HANDLE_UNKNOWN_CURVE_TYPE Unsupported elliptic curve type * @retval HITLS_MSG_HANDLE_UNSUPPORT_NAMED_CURVE Unsupported ECDH elliptic curve */ int32_t HS_ProcessClientKxMsgEcdhe(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg); /** * @brief Process the server DH key exchange message * * @param ctx [IN] TLS context * @param serverKxMsg [IN] Parsed handshake message * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_MSG_HANDLE_ERR_ENCODE_DH_KEY Failed to obtain the DH public key. */ int32_t HS_ProcessServerKxMsgDhe(TLS_Ctx *ctx, const ServerKeyExchangeMsg *serverKxMsg); /** * @brief Process the client DH key exchange message * * @param ctx [IN] TLS context * @param clientKxMsg [IN] Parsed handshake message * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMALLOC_FAIL Memory application failed. */ int32_t HS_ProcessClientKxMsgDhe(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg); int32_t HS_ProcessClientKxMsgRsa(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg); int32_t HS_ProcessClientKxMsgSm2(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg); /** * @brief Derive the master secret. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG Unsupported Key Exchange Algorithm * @retval For other error codes, see SAL_CRYPT_CalcEcdhSharedSecret. */ int32_t HS_GenerateMasterSecret(TLS_Ctx *ctx); /** * @brief Process the identity hint contained in ServerKeyExchange during PSK negotiation. * * @param ctx [IN] TLS context * @param serverKxMsg [IN] Parsed handshake message * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK The callback for obtaining the PSK on the client is not set. * @retval HITLS_CONFIG_INVALID_LENGTH The length of the prompt message is incorrect. * @retval HITLS_MEMALLOC_FAIL Memory application failed. */ int32_t HS_ProcessServerKxMsgIdentityHint(TLS_Ctx *ctx, const ServerKeyExchangeMsg *serverKxMsg); /** * @brief TLS1.3 derived secret * * @param deriveInfo [IN] secret derivation material * @param isHashed [IN] true: indicates that the seed has been hashed false: indicates that the seed has not been * hashed. * @param outSecret [OUT] Output secret * @param outLen [IN] Output secret length * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. */ int32_t HS_TLS13DeriveSecret(CRYPT_KeyDeriveParameters *deriveInfo, bool isHashed, uint8_t *outSecret, uint32_t outLen); int32_t HS_TLS13DeriveBinderKey(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, bool isExternalPsk, uint8_t *earlySecret, uint32_t secretLen, uint8_t *binderKey, uint32_t keyLen); /** * @brief TLS1.3 Calculate the early secret. * * @param hashAlg [IN] secret derivation material * @param psk [IN] PSK * @param pskLen [OUT] PSK length * @param earlySecret [IN] Output secret * @param outLen [IN] Output secret length * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_HKDF_EXTRACT HKDF-Extract calculation failure */ int32_t HS_TLS13DeriveEarlySecret(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, uint8_t *psk, uint32_t pskLen, uint8_t *earlySecret, uint32_t *outLen); /** * @brief TLS1.3 Calculate the secret in the next phase. * * @param hashAlg [IN] Hash algorithm * @param inSecret [IN] secret of the current phase * @param inLen [OUT] Current secret length * @param givenSecret [IN] The secret specified by the * @param givenLen [IN] Specify the secret length. * @param outSecret [IN] Output secret * @param outLen [IN/OUT] IN: Maximum buffer length OUT: Output secret length * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXTRACT HKDF-Extract calculation failure */ int32_t HS_TLS13DeriveNextStageSecret(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, uint8_t *inSecret, uint32_t inLen, uint8_t *givenSecret, uint32_t givenLen, uint8_t *outSecret, uint32_t *outLen); /** * @brief TLS1.3 Calculate the FinishedKey. * * @param hashAlg [IN] Hash algorithm * @param baseKey [IN] Key of the current phase * @param baseKeyLen [IN] Current key length * @param finishedkey [OUT] Output key * @param finishedkeyLen [IN] Output key length * * @retval HITLS_SUCCESS succeeded. * @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 HS_TLS13DeriveFinishedKey(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, uint8_t *baseKey, uint32_t baseKeyLen, uint8_t *finishedkey, uint32_t finishedkeyLen); /** * @brief TLS1.3 Switch the traffickey. * * @param ctx [IN] TLS context * @param secret [IN] secret for calculating writekey and writeiv * @param secretLen [IN] Input the secret length. * @param isOut [IN] It is used to determine writeSate and readState. * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation failed. * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer */ int32_t HS_SwitchTrafficKey(TLS_Ctx *ctx, uint8_t *secret, uint32_t secretLen, bool isOut); /** * @brief Set parameters for initializing the panding state of the record layer. * * @param ctx [IN] TLS context * @param isClient [IN] Whether it is a client * @param keyPara [OUT] Output parameter * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMCPY_FAIL Memory Copy Failure */ int32_t HS_SetInitPendingStateParam(const TLS_Ctx *ctx, bool isClient, REC_SecParameters *keyPara); /** * @brief TLS1.3 Derives the secret of the ServerHello procedure. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXTRACT HKDF-Extract calculation failed. * @retval HITLS_CRYPT_ERR_CALC_SHARED_KEY Failed to calculate the shared key. * @retval HITLS_CRYPT_ERR_DIGEST hash calculation fails. * @retval For details about other error codes, see the SAL_CRYPT_DigestFinal interface. */ int32_t HS_TLS13CalcServerHelloProcessSecret(TLS_Ctx *ctx); /** * @brief TLS1.3 Derives the secret of the ServerFinish process. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation failed. * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXTRACT HKDF-Extract calculation failed. * @retval For details about other error codes, see the SAL_CRYPT_DigestFinal interface. */ int32_t HS_TLS13CalcServerFinishProcessSecret(TLS_Ctx *ctx); /** * @brief TLS1.3 Update the traffic secret. * * @param ctx [IN] TLS context * @param isOut [IN] It is used to determine writeSate and readState. * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation failed. * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXTRACT HKDF-Extract calculation failure * @retval For other error codes, see the SAL_CRYPT_DigestFinal interface. */ int32_t HS_TLS13UpdateTrafficSecret(TLS_Ctx *ctx, bool isOut); /** * @brief TLS1.3 Derived by resumption_master_secret * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXTRACT HKDF-Extract calculation failure * @retval HITLS_CRYPT_ERR_CALC_SHARED_KEY Failed to calculate the shared key. * @retval HITLS_CRYPT_ERR_DIGEST hash calculation failed. * @retval For other error codes, see the SAL_CRYPT_DigestFinal interface */ int32_t HS_TLS13DeriveResumptionMasterSecret(TLS_Ctx *ctx); /** * @brief TLS1.3 calculate session resumption PSK * * @param ctx [IN] TLS context * @param ticketNonce [IN] Unique ID of the ticket issued on the, which is used to calculate the PSK for session * resumption. * @param ticketNonceSize [IN] ticketNonce length * @param resumePsk [OUT] Output the PSK key. * @param resumePskLen [IN] Output the PSK length. * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation fails. * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails. */ int32_t HS_TLS13DeriveResumePsk( TLS_Ctx *ctx, const uint8_t *ticketNonce, uint32_t ticketNonceSize, uint8_t *resumePsk, uint32_t resumePskLen); int32_t HS_TLS13DeriveHandshakeTrafficSecret(TLS_Ctx *ctx); #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
tls/handshake/common/include/hs_kx.h
C
unknown
12,151
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_MSG_H #define HS_MSG_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "bsl_module_list.h" #include "cert.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define HS_MSG_HEADER_SIZE 4u #define DTLS_HS_MSG_HEADER_SIZE 12u #define HS_RANDOM_SIZE 32u #define HS_RANDOM_DOWNGRADE_SIZE 8u #define TLS_HS_MAX_SESSION_ID_SIZE 32u #define TLS_HS_MIN_SESSION_ID_SIZE 24u #define TLS_HS_MIN_COOKIE_SIZE 1u #define TLS_HS_MAX_COOKIE_SIZE 255u #define DTLS_HS_MSGLEN_ADDR 1u /* DTLS message length address, which is used when parsing the DTLS message header. */ /* DTLS message sequence number address, which is used for parsing the DTLS message header. */ #define DTLS_HS_MSGSEQ_ADDR 4u /* DTLS message fragment offset address, which is used when the DTLS message header is parsed. */ #define DTLS_HS_FRAGMENT_OFFSET_ADDR 6u /* DTLS message fragment length address, which is used when parsing the DTLS message header. */ #define DTLS_HS_FRAGMENT_LEN_ADDR 9u /* Handshake message type */ typedef enum { HELLO_REQUEST = 0, CLIENT_HELLO = 1, SERVER_HELLO = 2, HELLO_VERIFY_REQUEST = 3, NEW_SESSION_TICKET = 4, END_OF_EARLY_DATA = 5, HELLO_RETRY_REQUEST = 6, ENCRYPTED_EXTENSIONS = 8, CERTIFICATE = 11, SERVER_KEY_EXCHANGE = 12, CERTIFICATE_REQUEST = 13, SERVER_HELLO_DONE = 14, CERTIFICATE_VERIFY = 15, CLIENT_KEY_EXCHANGE = 16, FINISHED = 20, CERTIFICATE_URL = 21, CERTIFICATION_STATUS = 22, SUPPLEMENTAL_DATA = 23, KEY_UPDATE = 24, MESSAGE_HASH = 254, HS_MSG_TYPE_END = 255 } HS_MsgType; typedef enum { PSK_KE = 0, PSK_DHE_KE = 1, PSK_KEY_EXCHANGEMODE_END = 255 } HS_PskKeyExchMode; typedef struct { HITLS_KeyUpdateRequest requestUpdate; } KeyUpdateMsg; typedef struct { ListHead head; uint16_t group; /* Naming group of keys to be exchanged */ uint16_t keyExchangeSize; uint8_t *keyExchange; /* Key exchange information */ } KeyShare; typedef struct OfferedPsks { ListHead pskNode; /* Multiple PSK linked lists are formed through pskNode. The actual data of this node is the following fields */ uint8_t *identity; /* pskid and binder are in one-to-one mapping. */ uint8_t *binder; /* HMAC value */ uint32_t obfuscatedTicketAge; /* An obfuscated version of the age of the key */ uint16_t identitySize; /* bytes of identity */ uint8_t binderSize; /* bytes of binder */ bool isValid; /* is binder valid */ } PreSharedKey; typedef struct { uint16_t *supportedGroups; uint16_t *signatureAlgorithms; uint16_t *signatureAlgorithmsCert; uint8_t *pointFormats; uint8_t *alpnList; /* application-layer protocol negotiation list */ uint8_t *serverName; /* serverName after parsing */ uint8_t *secRenegoInfo; /* renegotiation extension information */ uint8_t *ticket; /* ticket information */ uint32_t ticketSize; uint16_t supportedGroupsSize; uint16_t signatureAlgorithmsSize; uint16_t signatureAlgorithmsCertSize; uint16_t alpnListSize; /* application-layer protocol negotiation list len */ uint16_t serverNameSize; uint8_t pointFormatsSize; uint8_t serverNameType; /* Type of the parsed serverName. */ uint8_t secRenegoInfoSize; /* Length of the security renegotiation information */ uint8_t reserved[1]; /* Four-byte alignment */ /* TLS1.3 */ uint16_t *supportedVersions; uint8_t *cookie; uint8_t *keModes; uint8_t keModesSize; uint8_t supportedVersionsCount; /* Number of supported version */ uint16_t cookieLen; HITLS_TrustedCAList *caList; PreSharedKey *preSharedKey; KeyShare *keyShare; /* In the ClientHello message, this extension provides a set of KeyShares */ } ExtensionContent; typedef struct { bool haveSupportedGroups; bool haveSignatureAlgorithms; bool haveSignatureAlgorithmsCert; bool havePointFormats; bool haveExtendedMasterSecret; bool haveSupportedVers; bool haveCookie; /* Whether there is a cookie (involved in TLS1.3 ClientHello) */ bool haveCA; /* Whether the CA exists (involved in TLS1.3 ClientHello) */ bool havePostHsAuth; /* Indicates whether the Client (TLS1.3) is willing to receive the Certificate Request message. */ bool haveKeyShare; bool haveEarlyData; bool havePskExMode; /* Indicates whether the TLS1.3 key exchange mode exists. */ bool havePreShareKey; /* Indicates whether the pre-shared key exists. */ bool haveAlpn; /* Whether there is Alpn */ bool haveServerName; /* Whether the ServerName extension exists. */ bool haveSecRenego; /* Whether security renegotiation exists. */ bool haveTicket; /* Indicates whether a ticket is available. */ bool haveEncryptThenMac; /* Indicates whether EncryptThenMac is supported. */ } ExtensionFlag; typedef struct { ExtensionFlag flag; ExtensionContent content; } ClientHelloExt; /* It is used to transmit client hello message */ typedef struct { uint8_t randomValue[HS_RANDOM_SIZE]; /* random number group */ uint8_t *sessionId; uint8_t *cookie; /* Cookie (for DTLS only) */ uint16_t *cipherSuites; uint16_t version; uint16_t cipherSuitesSize; uint8_t sessionIdSize; uint8_t compressionMethodsSize; uint8_t *compressionMethods; uint8_t cookieLen; bool haveEmptyRenegoScsvCipher; /* According to RFC 5746, a special signaling cipher suite value (SCSV) can be used to indicate that security renegotiation is supported. */ bool haveFallBackScsvCipher; /* According to RFC 7507, a special signaling cipher suite value (SCSV) can be used to indicate that a downgrade negotiation process is in progress. */ uint8_t refCnt; /* Do not involve multiple threads. Process the hrr check clientHello. */ uint32_t truncateHelloLen; /* is used for binder calculation. */ ClientHelloExt extension; uint64_t extensionTypeMask; uint8_t *extensionBuff; uint32_t extensionBuffLen; uint8_t extensionCount; /* Size of the extension buffer */ } ClientHelloMsg; /* It is used to transmit server hello message */ typedef struct { uint16_t version; uint16_t cipherSuite; uint8_t randomValue[HS_RANDOM_SIZE]; /* random number group */ uint8_t *sessionId; uint8_t *pointFormats; uint8_t *alpnSelected; /* selected alpn protocol */ uint8_t *cookie; uint8_t *secRenegoInfo; KeyShare keyShare; uint16_t alpnSelectedSize; /* selected alpn protocol length */ uint16_t supportedVersion; uint16_t cookieLen; uint16_t selectedIdentity; /* TLS 1.3 psk required */ uint8_t sessionIdSize; uint8_t pointFormatsSize; uint8_t secRenegoInfoSize; /* Length of the security renegotiation information */ uint64_t extensionTypeMask; bool havePointFormats; bool haveExtendedMasterSecret; bool haveSupportedVersion; bool haveCookie; /* Indicates whether the cookie length is involved in TLS1.3 HelloRetryRequest. */ bool haveKeyShare; /* Whether KeyShare is extended. */ bool haveSelectedIdentity; /* Indicates whether the Pre_PSK is selected. */ bool haveSelectedAlpn; /* Whether the application layer protocol is selected. */ bool haveServerName; bool haveSecRenego; bool haveTicket; bool haveEncryptThenMac; bool reserved[2]; /* Four-byte alignment */ } ServerHelloMsg; /* It is used to transmit hello verify request message */ typedef struct { uint16_t version; uint8_t cookieLen; uint8_t reserved[1]; /* fill with 1 byte for 4-byte alignment */ uint8_t *cookie; } HelloVerifyRequestMsg; /* Transmits certificate message */ typedef struct { CERT_Item *cert; /* Certificate message content */ uint32_t certCount; /* Number of certificates */ uint8_t *certificateReqCtx; /* Used by the TLS 1.3 */ uint32_t certificateReqCtxSize; /* Used by the TLS 1.3 */ uint64_t extensionTypeMask; /* Used by the TLS 1.3 */ } CertificateMsg; typedef struct { HITLS_ECParameters ecPara; /* Elliptic curve field parameter of the ECDH public key */ uint32_t pubKeySize; /* Length of the ecdh public key */ uint8_t *pubKey; /* ecdh public key content */ uint16_t signAlgorithm; uint16_t signSize; uint8_t *signData; } ServerEcdh; typedef struct { uint8_t *p; uint8_t *g; uint16_t plen; uint16_t glen; uint8_t *pubkey; uint16_t pubKeyLen; uint16_t signAlgorithm; uint16_t signSize; uint8_t *signData; } ServerDh; /* Used to transfer the key exchange content of the server */ typedef struct { uint8_t *pskIdentityHint; /* psk identity negotiation prompt message */ uint32_t hintSize; HITLS_KeyExchAlgo keyExType; /* key exchange mode */ union { ServerEcdh ecdh; ServerDh dh; } keyEx; } ServerKeyExchangeMsg; /* Used to transfer the client key exchange content */ typedef struct { uint8_t *pskIdentity; uint32_t pskIdentitySize; uint32_t dataSize; /* Key exchange data length */ uint8_t *data; /* Key exchange data. */ } ClientKeyExchangeMsg; /* Transmits certificate request message */ typedef struct { uint8_t *certTypes; uint16_t *signatureAlgorithms; uint8_t reserved; /* Four-byte alignment */ uint8_t certTypesSize; uint16_t signatureAlgorithmsSize; #ifdef HITLS_TLS_PROTO_TLS13 uint16_t *signatureAlgorithmsCert; uint16_t signatureAlgorithmsCertSize; uint8_t *certificateReqCtx; /* Used by the TLS 1.3 */ uint32_t certificateReqCtxSize; /* This field is used by the TLS 1.3. The value is not 0 only for the authentication after the handshake */ uint64_t extensionTypeMask; bool haveSignatureAndHashAlgoCert; #endif /* HITLS_TLS_PROTO_TLS13 */ bool haveSignatureAndHashAlgo; bool haveDistinguishedName; } CertificateRequestMsg; /* Transmits certificate verification message */ typedef struct { uint16_t signHashAlg; /* Signature hash algorithm, which is available only for TLS1.2 and DTLS1.2 */ uint16_t signSize; /* Length of the signature data. */ uint8_t *sign; /* Signature data */ } CertificateVerifyMsg; /* It is used to transmit Ticket message RFC5077 3.3 NewSessionTicket Handshake Message struct { uint32 ticket_lifetime_hint; opaque ticket<0..2^16-1>; } NewSessionTicket; TLS1.3: struct { uint32 ticket_lifetime; uint32 ticket_age_add; opaque ticket_nonce<0..255>; opaque ticket<1..2^16-1>; Extension extensions<0..2^16-2>; } NewSessionTicket; */ typedef struct { uint32_t ticketLifetimeHint; /* ticket timeout interval, in seconds */ uint32_t ticketAgeAdd; /* ticket_age_add: a random number generated each time a ticket is issued. */ uint32_t ticketNonceSize; /* ticket_nonce length */ uint8_t *ticketNonce; /* ticketNonce: Unique ID of the ticket issued on the connection, starting from 0 and increasing in ascending order. */ uint32_t ticketSize; uint8_t *ticket; /* ticket */ uint64_t extensionTypeMask; } NewSessionTicketMsg; /* It is used to transmit finish message */ typedef struct { uint32_t verifyDataSize; uint8_t *verifyData; } FinishedMsg; typedef struct { uint16_t *supportedGroups; uint16_t supportedGroupsSize; uint16_t alpnSelectedSize; /* selected alpn protocol length */ uint8_t *alpnSelected; /* selected alpn protocol */ uint64_t extensionTypeMask; bool haveSupportedGroups; bool haveEarlyData; bool haveServerName; bool haveSelectedAlpn; } EncryptedExtensions; /* Used to parse the handshake message header. */ typedef struct { HS_MsgType type; uint32_t length; /* handshake msg body length */ uint16_t sequence; /* DTLS Indicates the number of the handshake message. Each time a new handshake message is sent, one is added. Retransmission does not add up */ uint32_t fragmentOffset; /* Fragment offset of DTLS handshake message */ uint32_t fragmentLength; /* Fragment length of the DTLS handshake message */ const uint8_t *rawMsg; /* Complete handshake information */ uint32_t headerAndBodyLen; } HS_MsgInfo; /* It is used to transmit handshake message */ typedef struct { HS_MsgType type; uint32_t length; uint16_t sequence; /* DTLS Indicates the number of the handshake message. Each time a new handshake message is sent, one is added. Retransmission does not add up */ uint8_t reserved[2]; /* fill 2 bytes for 4-byte alignment. */ uint32_t fragmentOffset; /* Fragment offset of DTLS handshake message. */ uint32_t fragmentLength; /* Fragment length of the DTLS handshake message */ union { ClientHelloMsg clientHello; ServerHelloMsg serverHello; HelloVerifyRequestMsg helloVerifyReq; EncryptedExtensions encryptedExtensions; CertificateMsg certificate; ClientKeyExchangeMsg clientKeyExchange; ServerKeyExchangeMsg serverKeyExchange; CertificateRequestMsg certificateReq; CertificateVerifyMsg certificateVerify; NewSessionTicketMsg newSessionTicket; FinishedMsg finished; KeyUpdateMsg keyUpdate; } body; } HS_Msg; #ifdef HITLS_TLS_PROTO_DTLS12 /* Reassembles fragmented messages */ typedef struct { ListHead head; HS_MsgType type; uint16_t sequence; /* DTLS Indicates the number of the handshake message. Each time a new handshake message is sent, one is added. Retransmission does not add up */ bool isReassComplete; /* Indicates whether the message is reassembled. */ uint8_t reserved; /* Padded with 1 byte for 4-byte alignment. */ uint8_t *reassBitMap; /* bitmap, used for processing duplicate fragmented message and calculating whether the fragmented message are completely reassembled. */ uint8_t *msg; /* Used to store the handshake messages during the reassembly. */ uint32_t msgLen; /* Total length of a message, including the message header. */ } HS_ReassQueue; #endif #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_MSG_H */
2301_79861745/bench_create
tls/handshake/common/include/hs_msg.h
C
unknown
15,261
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_VERIFY_H #define HS_VERIFY_H #include <stdint.h> #include <stdbool.h> #include "hitls_crypt_type.h" #include "tls.h" #include "hs_ctx.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize the verify context * @attention If it has been initialized, the verify context will be reset * * @param hsCtx [IN] Handshake context * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocation failed */ int32_t VERIFY_Init(HS_Ctx *hsCtx); /** * @brief Release verify context * * @param hsCtx [IN] Handshake context */ void VERIFY_Deinit(HS_Ctx *hsCtx); /** * @brief Calculate verify data * * @param ctx [IN] tls Context * @param isClient [IN] Indicates whether the context is client. If yes, the system calculates the verify data * sent by the client. Otherwise, the system calculates the verify data sent by the server. * @param masterSecret [IN] * @param masterSecretLen [IN] * * @retval HITLS_SUCCESS * @retval HITLS_UNREGISTERED_CALLBACK Callback unregistered * @retval HITLS_CRYPT_ERR_DIGEST Hash operation failed * @retval HITLS_CRYPT_ERR_HMAC HMAC operation failed * @retval HITLS_MEMALLOC_FAIL Memory allocation failed */ int32_t VERIFY_CalcVerifyData(TLS_Ctx *ctx, bool isClient, const uint8_t *masterSecret, uint32_t masterSecretLen); /** * @brief Calculate the client verify signature data * * @param ctx [IN] TLS context. Different TLS and DTLS versions require different processing * @param privateKey [IN] Certificate private key * @param signScheme [IN] Signature hash algorithm * * @retval HITLS_SUCCESS * @retval HITLS_PACK_SIGNATURE_ERR Signing failed */ int32_t VERIFY_CalcSignData(TLS_Ctx *ctx, HITLS_CERT_Key *privateKey, HITLS_SignHashAlgo signScheme); /** * @brief Verify the client signature data * * @param ctx [IN] TLS context. Different TLS and DTLS versions require different processing * @param pubkey [IN] Public key of the device certificate * @param signScheme [IN] Signature hash algorithm * @param signData [IN] Signature * @param signDataLen [IN] Signature length * * @retval HITLS_SUCCESS * @retval HITLS_PACK_SIGNATURE_ERR Signing failed */ int32_t VERIFY_VerifySignData(TLS_Ctx *ctx, HITLS_CERT_Key *pubkey, HITLS_SignHashAlgo signScheme, const uint8_t *signData, uint16_t signDataLen); /** * @brief Obtain the verify data * * @param ctx [IN] verify context * @param verifyData [OUT] * @param verifyDataLen [IN/OUT] IN: maximum length of data OUT:verify data Len * * @retval HITLS_SUCCESS * @retval HITLS_MEMCPY_FAIL Memory copy failed */ int32_t VERIFY_GetVerifyData(const VerifyCtx *ctx, uint8_t *verifyData, uint32_t *verifyDataLen); /** * @brief TLS1.3 calculate verify data * * @param ctx [IN] TLS Context * @param isClient [IN] Indicates whether the context is client. If yes, the system calculates the verify data * sent by the client. Otherwise, the system calculates the verify data sent by the server. * @retval HITLS_SUCCESS * @retval HITLS_UNREGISTERED_CALLBACK Callback unregistered * @retval HITLS_CRYPT_ERR_DIGEST Hash operation failed * @retval HITLS_CRYPT_ERR_HMAC HMAC operation failed * @retval HITLS_MEMALLOC_FAIL Memory allocation failed */ int32_t VERIFY_Tls13CalcVerifyData(TLS_Ctx *ctx, bool isClient); /** * @brief Reprocess the verify data for the hello retry request message * * @param ctx [IN] TLS Context * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t VERIFY_HelloRetryRequestVerifyProcess(TLS_Ctx *ctx); int32_t VERIFY_CalcPskBinder(const TLS_Ctx *ctx, HITLS_HashAlgo hashAlgo, bool isExternalPsk, uint8_t *psk, uint32_t pskLen, const uint8_t *msg, uint32_t msgLen, uint8_t *binder, uint32_t binderLen); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_VERIFY_H */
2301_79861745/bench_create
tls/handshake/common/include/hs_verify.h
C
unknown
4,514
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef TRANSCRIPT_HASH_H #define TRANSCRIPT_HASH_H #include <stdint.h> #include "hitls_crypt_type.h" #include "hs_ctx.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Set the hash algorithm * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param ctx [IN] verify context * @param hashAlgo [IN] hash algorithm * * @retval HITLS_SUCCESS * @retval HITLS_CRYPT_ERR_DIGEST hash operation failed * @retval HITLS_UNREGISTERED_CALLBACK The callback function is not registered. */ int32_t VERIFY_SetHash(HITLS_Lib_Ctx *libCtx, const char *attrName, VerifyCtx *ctx, HITLS_HashAlgo hashAlgo); /** * @brief Add handshake message data * * @param ctx [IN] verify context * @param data [IN] Handshake message data * @param len [IN] Data length * * @retval HITLS_SUCCESS * @retval HITLS_UNREGISTERED_CALLBACK The callback function is not registered. * @retval HITLS_CRYPT_ERR_DIGEST hash operation failed * @retval HITLS_MEMCPY_FAIL * @retval HITLS_MEMALLOC_FAIL */ int32_t VERIFY_Append(VerifyCtx *ctx, const uint8_t *data, uint32_t len); /** * @brief Calculate the SessionHash * * @param ctx [IN] verify context * @param digest [OUT] digest data * @param digestLen [IN/OUT] IN:maximum length of digest OUT:digest length * * @retval HITLS_SUCCESS * @retval For other error codes, see SAL_CRYPT_DigestFinal */ int32_t VERIFY_CalcSessionHash(VerifyCtx *ctx, uint8_t *digest, uint32_t *digestLen); /** * @brief Release the message cache linked list * * @param ctx [IN] verify context */ void VERIFY_FreeMsgCache(VerifyCtx *ctx); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end TRANSCRIPT_HASH_H */
2301_79861745/bench_create
tls/handshake/common/include/transcript_hash.h
C
unknown
2,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. */ #include <string.h> #include "hitls_build.h" #include "securec.h" #include "bsl_bytes.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 "hitls.h" #include "hitls_error.h" #include "tls_config.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "uio_base.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif /* HITLS_TLS_FEATURE_INDICATOR */ #include "pack.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "parse.h" #include "hs_kx.h" #include "hs.h" #include "hs_extensions.h" #include "hs_common.h" #include "config_type.h" #include "config_check.h" #include "record.h" #ifdef HITLS_TLS_PROTO_DTLS12 #define DTLS_SCTP_AUTH_LABEL "EXPORTER_DTLS_OVER_SCTP" /* dtls SCTP auth key label */ #endif #ifdef HITLS_TLS_PROTO_TLS13 /* Fixed random value of the hello retry request packet */ const uint8_t g_hrrRandom[HS_RANDOM_SIZE] = { 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c }; const uint8_t *HS_GetHrrRandom(uint32_t *len) { *len = HS_RANDOM_SIZE; return g_hrrRandom; } #ifdef HITLS_TLS_PROTO_TLS_BASIC const uint8_t g_tls12Downgrade[HS_DOWNGRADE_RANDOM_SIZE] = { 0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01 }; const uint8_t *HS_GetTls12DowngradeRandom(uint32_t *len) { *len = HS_DOWNGRADE_RANDOM_SIZE; return g_tls12Downgrade; } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #endif /* HITLS_TLS_PROTO_TLS13 */ uint32_t HS_GetVersion(const TLS_Ctx *ctx) { if (ctx->negotiatedInfo.version > 0) { return ctx->negotiatedInfo.version; } else { /* If the version is not negotiated, the latest version supported by the local is returned */ return ctx->config.tlsConfig.maxVersion; } } static const char *g_stateMachineStr[] = { [TLS_IDLE] = "idle", [TLS_CONNECTED] = "connected", #ifdef HITLS_TLS_HOST_CLIENT [TRY_SEND_CLIENT_HELLO] = "send client hello", [TRY_SEND_CLIENT_KEY_EXCHANGE] = "send client key exchange", [TRY_RECV_SERVER_HELLO] = "recv server hello", [TRY_RECV_HELLO_VERIFY_REQUEST] = "recv hello verify request", [TRY_RECV_SERVER_KEY_EXCHANGE] = "recv server key exchange", [TRY_RECV_SERVER_HELLO_DONE] = "recv server hello done", [TRY_RECV_NEW_SESSION_TICKET] = "recv new session ticket", [TRY_RECV_HELLO_REQUEST] = "recv hello request", #endif #ifdef HITLS_TLS_HOST_SERVER [TRY_SEND_HELLO_REQUEST] = "send hello request", [TRY_SEND_SERVER_HELLO] = "send server hello", [TRY_SEND_HELLO_VERIFY_REQUEST] = "send hello verify request", [TRY_SEND_SERVER_KEY_EXCHANGE] = "send server key exchange", [TRY_RECV_CLIENT_HELLO] = "recv client hello", [TRY_RECV_CLIENT_KEY_EXCHANGE] = "recv client key exchange", [TRY_SEND_SERVER_HELLO_DONE] = "send server hello done", [TRY_SEND_NEW_SESSION_TICKET] = "send new session ticket", #endif #ifdef HITLS_TLS_PROTO_TLS13 [TRY_RECV_KEY_UPDATE] = "recv keyupdate", [TRY_SEND_KEY_UPDATE] = "send keyupdate", #ifdef HITLS_TLS_HOST_CLIENT [TRY_RECV_ENCRYPTED_EXTENSIONS] = "recv encrypted extensions", [TRY_SEND_END_OF_EARLY_DATA] = "send end of early data", #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER [TRY_SEND_ENCRYPTED_EXTENSIONS] = "send encrypted extensions", [TRY_SEND_HELLO_RETRY_REQUEST] = "send hello retry request", [TRY_RECV_END_OF_EARLY_DATA] = "recv end of early data", #endif /* HITLS_TLS_HOST_SERVER */ #endif /* HITLS_TLS_PROTO_TLS13 */ [TRY_SEND_CERTIFICATE] = "send certificate", [TRY_SEND_CERTIFICATE_REQUEST] = "send certificate request", [TRY_SEND_CERTIFICATE_VERIFY] = "send certificate verify", [TRY_SEND_CHANGE_CIPHER_SPEC] = "send change cipher spec", [TRY_RECV_CERTIFICATE] = "recv certificate", [TRY_RECV_CERTIFICATE_REQUEST] = "recv certificate request", [TRY_RECV_CERTIFICATE_VERIFY] = "recv certificate verify", [TRY_RECV_FINISH] = "recv finished", [TRY_SEND_FINISH] = "send finished", }; const char *HS_GetStateStr(uint32_t state) { if ((state >= (sizeof(g_stateMachineStr) / sizeof(char *))) || (g_stateMachineStr[state] == NULL)) { return "unknown"; } return g_stateMachineStr[state]; } const char *HS_GetMsgTypeStr(HS_MsgType type) { switch (type) { case HELLO_REQUEST: return "hello request"; case CLIENT_HELLO: return "client hello"; case SERVER_HELLO: return "server hello"; #ifdef HITLS_TLS_PROTO_TLS13 case ENCRYPTED_EXTENSIONS: return "encrypted extensions"; #endif case CERTIFICATE: return "certificate"; case SERVER_KEY_EXCHANGE: return "server key exchange"; case CERTIFICATE_REQUEST: return "certificate request"; case SERVER_HELLO_DONE: return "server hello done"; case CERTIFICATE_VERIFY: return "certificate verify"; case CLIENT_KEY_EXCHANGE: return "client key exchange"; case NEW_SESSION_TICKET: return "new session ticket"; case FINISHED: return "finished"; default: break; } return "unknown"; } int32_t HS_ChangeState(TLS_Ctx *ctx, uint32_t nextState) { HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; hsCtx->state = nextState; #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0) { if (hsCtx->state == TLS_CONNECTED) { RecTryFreeRecBuf(ctx, false); RecTryFreeRecBuf(ctx, true); } else if (IsHsSendState(hsCtx->state)) { RecTryFreeRecBuf(ctx, false); } else { RecTryFreeRecBuf(ctx, true); } } #endif /* when link state is transporting, unexpected hs message should be processed, the log shouldn't be printed during the hsCtx initiation */ if (ctx->state != CM_STATE_TRANSPORTING) { #ifdef HITLS_TLS_FEATURE_INDICATOR if (ctx->isClient) { INDICATOR_StatusIndicate(ctx, INDICATE_EVENT_STATE_CONNECT_LOOP, INDICATE_VALUE_SUCCESS); } else { INDICATOR_StatusIndicate(ctx, INDICATE_EVENT_STATE_ACCEPT_LOOP, INDICATE_VALUE_SUCCESS); } #endif /* HITLS_TLS_FEATURE_INDICATOR */ BSL_LOG_BINLOG_VARLEN(BINLOG_ID15573, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "handshake state machine change to:%s.", HS_GetStateStr(nextState)); } return HITLS_SUCCESS; } int32_t HS_CombineRandom(const uint8_t *random1, const uint8_t *random2, uint32_t randomSize, uint8_t *dest, uint32_t destSize) { /** If the random number length is 0 or the memory address is less than twice the random number length, return an * error code. */ if ((randomSize == 0u) || (destSize < randomSize * 2)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RANDOM_SIZE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15574, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid randomSize for combine random.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_RANDOM_SIZE_ERR; } if (memcpy_s(dest, destSize, random1, randomSize) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15575, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "combine random1 fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } if (memcpy_s(&dest[randomSize], destSize - randomSize, random2, randomSize) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15576, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "combine random2 fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLCP11 uint8_t *HS_PrepareSignDataTlcp(const TLS_Ctx *ctx, const uint8_t *partSignData, uint32_t partSignDataLen, uint32_t *signDataLen) { /* Signature data: client random number + server random number + exchange parameter length + key exchange packet * data/encryption certificate */ uint32_t exchParamLen = 3; uint32_t randomLen = HS_RANDOM_SIZE * 2u; uint32_t dataLen = randomLen + partSignDataLen + exchParamLen; uint8_t *data = BSL_SAL_Calloc(1u, dataLen); if (data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15577, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "signature data memory alloc fail.", 0, 0, 0, 0); return NULL; } (void)memcpy_s(data, dataLen, ctx->hsCtx->clientRandom, HS_RANDOM_SIZE); (void)memcpy_s(&data[HS_RANDOM_SIZE], dataLen - HS_RANDOM_SIZE, ctx->hsCtx->serverRandom, HS_RANDOM_SIZE); /* Fill the length of the key exchange parameter */ BSL_Uint24ToByte(partSignDataLen, &data[randomLen]); /* Copy key exchange packet data */ (void)memcpy_s(&data[randomLen] + exchParamLen, dataLen - randomLen - exchParamLen, partSignData, partSignDataLen); *signDataLen = dataLen; return data; } #endif uint8_t *HS_PrepareSignData(const TLS_Ctx *ctx, const uint8_t *partSignData, uint32_t partSignDataLen, uint32_t *signDataLen) { int32_t ret; /* Signature data: client random number + server random number + key exchange packet data/encryption certificate */ uint32_t randomLen = HS_RANDOM_SIZE * 2u; uint32_t dataLen = randomLen + partSignDataLen; uint8_t *data = BSL_SAL_Calloc(1u, dataLen); if (data == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16813, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return NULL; } (void)memcpy_s(data, dataLen, ctx->hsCtx->clientRandom, HS_RANDOM_SIZE); (void)memcpy_s(&data[HS_RANDOM_SIZE], dataLen - HS_RANDOM_SIZE, ctx->hsCtx->serverRandom, HS_RANDOM_SIZE); /* Copy key exchange packet data */ ret = memcpy_s(&data[randomLen], dataLen - randomLen, partSignData, partSignDataLen); if (ret != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16814, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); BSL_SAL_Free(data); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return NULL; } *signDataLen = dataLen; return data; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) /** * @brief Calculate the sctp auth key * @details auth key: PRF(SecurityParameters.master_secret, label, * SecurityParameters.client_random + * SecurityParameters.server_random)[length] * * @param ctx [IN] TLS context * @param authKey [OUT] Authorization key * @param authKeyLen [IN] Key length * * @retval HITLS_SUCCESS calculation is complete. * @retval HITLS_MSG_HANDLE_RANDOM_SIZE_ERR The random number length is incorrect. * @retval For other error codes, see SAL_CRYPT_PRF. */ int32_t CalcSctpAuthKey(const TLS_Ctx *ctx, uint8_t *authKey, uint32_t authKeyLen) { int32_t ret; uint8_t randomValue[HS_RANDOM_SIZE * 2] = {0}; // key derivation seed, with the length of two random characters uint32_t randomValueSize = HS_RANDOM_SIZE * 2; // key derivation seed, with the length of two random characters HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /** Combine the two random values */ ret = HS_CombineRandom(hsCtx->clientRandom, hsCtx->serverRandom, HS_RANDOM_SIZE, randomValue, randomValueSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15579, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "combine random fail.", 0, 0, 0, 0); return ret; } CRYPT_KeyDeriveParameters deriveInfo; deriveInfo.hashAlgo = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; deriveInfo.secret = hsCtx->masterKey; deriveInfo.secretLen = MASTER_SECRET_LEN; deriveInfo.label = (const uint8_t *)DTLS_SCTP_AUTH_LABEL; deriveInfo.labelLen = strlen(DTLS_SCTP_AUTH_LABEL); deriveInfo.seed = randomValue; deriveInfo.seedLen = randomValueSize; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); /** Key derivation */ ret = SAL_CRYPT_PRF(&deriveInfo, authKey, authKeyLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15580, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SAL_CRYPT_PRF fail when calc sctp auth key.", 0, 0, 0, 0); } return ret; } int32_t HS_SetSctpAuthKey(TLS_Ctx *ctx) { if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { return HITLS_SUCCESS; } int32_t ret; uint8_t authKey[DTLS_SCTP_SHARED_AUTHKEY_LEN] = {0}; uint16_t authKeyLen = sizeof(authKey); ret = CalcSctpAuthKey(ctx, authKey, authKeyLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15581, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "calc sctp auth key failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } /* If the UIO_SctpAddAuthKey is added but not active, return HITLS_SUCCESS when the interface is invoked again */ ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_SCTP_ADD_AUTH_SHARED_KEY, (int32_t)authKeyLen, authKey); /* Clear sensitive information */ BSL_SAL_CleanseData(authKey, DTLS_SCTP_SHARED_AUTHKEY_LEN); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_UIO_SCTP_ADD_AUTH_KEY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15582, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "uio add sctp auth shared key failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_UIO_SCTP_ADD_AUTH_KEY_FAIL; } return HITLS_SUCCESS; } int32_t HS_ActiveSctpAuthKey(TLS_Ctx *ctx) { if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { return HITLS_SUCCESS; } int32_t ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_SCTP_ACTIVE_AUTH_SHARED_KEY, 0, NULL); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15583, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "next sctp auth key error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_UIO_SCTP_ACTIVE_AUTH_KEY_FAIL; } return HITLS_SUCCESS; } int32_t HS_DeletePreviousSctpAuthKey(TLS_Ctx *ctx) { if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { return HITLS_SUCCESS; } /* After the handshake is complete, delete the old sctp auth key */ int32_t ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_SCTP_DEL_PRE_AUTH_SHARED_KEY, 0, NULL); if (ret != BSL_SUCCESS) { ret = HITLS_UIO_SCTP_DEL_AUTH_KEY_FAIL; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15584, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "uio delete sctp auth shared key failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); } return ret; } #endif /* defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) */ bool IsNeedServerKeyExchange(const TLS_Ctx *ctx) { HITLS_KeyExchAlgo kxAlg = ctx->negotiatedInfo.cipherSuiteInfo.kxAlg; /* Special: If the PSK identity hint is set, the PSK and RSA_PSK may also need to send * the ServerKeyExchange message */ if ((kxAlg == HITLS_KEY_EXCH_PSK) || (kxAlg == HITLS_KEY_EXCH_RSA_PSK)) { /* In this case, the client receives the ServerKeyExchange message by default */ if (ctx->isClient) { return true; } else { /* If the PSK identity hint is set on the server, the ServerKeyExchange message needs to be sent */ if (ctx->config.tlsConfig.pskIdentityHint != NULL) { return true; } return false; } } #ifdef HITLS_TLS_PROTO_TLCP11 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { return true; /* The TLCP needs to send the ServerKeyExchange message. */ } #endif /* The ECDH and DH certificates already contain the public key information, and the ServerKeyExchange message * is not required. */ /* RSA keys are generated by the client, and the ServerKeyExchange message is not required. */ return ((kxAlg != HITLS_KEY_EXCH_ECDH) && (kxAlg != HITLS_KEY_EXCH_DH) && (kxAlg != HITLS_KEY_EXCH_RSA)); } bool IsNeedCertPrepare(const CipherSuiteInfo *cipherSuiteInfo) { if (cipherSuiteInfo == NULL) { return false; } /* PSK related ciphersuite */ switch (cipherSuiteInfo->kxAlg) { case HITLS_KEY_EXCH_PSK: case HITLS_KEY_EXCH_DHE_PSK: case HITLS_KEY_EXCH_ECDHE_PSK: return false; default: break; } /* Anonymous ciphersuite related */ switch (cipherSuiteInfo->authAlg) { case HITLS_AUTH_NULL: return false; default: break; } return true; } bool IsTicketSupport(const TLS_Ctx *ctx) { #ifdef HITLS_TLS_FEATURE_SESSION_TICKET if (ctx->config.tlsConfig.isSupportSessionTicket && (!ctx->config.isSupportPto) #ifdef HITLS_TLS_FEATURE_SECURITY && (SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_TICKET, 0, 0, NULL) == SECURITY_SUCCESS) #endif ) { return true; } #endif (void)ctx; return false; } #ifdef HITLS_TLS_FEATURE_PSK bool IsPskNegotiation(const TLS_Ctx *ctx) { HITLS_KeyExchAlgo kxAlg = ctx->negotiatedInfo.cipherSuiteInfo.kxAlg; return ((kxAlg == HITLS_KEY_EXCH_ECDHE_PSK) || (kxAlg == HITLS_KEY_EXCH_DHE_PSK) || (kxAlg == HITLS_KEY_EXCH_RSA_PSK) || (kxAlg == HITLS_KEY_EXCH_PSK)); } int32_t CheckClientPsk(TLS_Ctx *ctx) { uint8_t psk[HS_PSK_MAX_LEN] = {0}; uint8_t identity[HS_PSK_IDENTITY_MAX_LEN + 1] = {0}; /* If the value of psk is not NULL, it has been processed. */ if (ctx->hsCtx->kxCtx->pskInfo != NULL && ctx->hsCtx->kxCtx->pskInfo->psk != NULL) { return HITLS_SUCCESS; } if (ctx->config.tlsConfig.pskClientCb == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16815, "unregistered pskClientCb"); } uint32_t pskUsedLen = ctx->config.tlsConfig.pskClientCb(ctx, NULL, identity, HS_PSK_IDENTITY_MAX_LEN, psk, HS_PSK_MAX_LEN); if (pskUsedLen == 0 || pskUsedLen > HS_PSK_IDENTITY_MAX_LEN) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN, BINLOG_ID16816, "pskUsedLen incorrect"); } /* Length of pskid will not exceed 128 bytes */ uint32_t identityUsedLen = (uint32_t)strnlen((char *)identity, HS_PSK_IDENTITY_MAX_LEN + 1); if (identityUsedLen > HS_PSK_IDENTITY_MAX_LEN) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return HITLS_MSG_HANDLE_ILLEGAL_IDENTITY_LEN; } if (ctx->hsCtx->kxCtx->pskInfo == NULL) { ctx->hsCtx->kxCtx->pskInfo = (PskInfo *)BSL_SAL_Calloc(1u, sizeof(PskInfo)); if (ctx->hsCtx->kxCtx->pskInfo == NULL) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16694, "Calloc fail"); } } uint8_t *tmpIdentity = NULL; if (identityUsedLen > 0) { tmpIdentity = (uint8_t *)BSL_SAL_Calloc(1u, (identityUsedLen + 1)); if (tmpIdentity == NULL) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16817, "Calloc fail"); } (void)memcpy_s(tmpIdentity, identityUsedLen + 1, identity, identityUsedLen); } ctx->hsCtx->kxCtx->pskInfo->psk = (uint8_t *)BSL_SAL_Dump(psk, pskUsedLen); (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); if (ctx->hsCtx->kxCtx->pskInfo->psk == NULL) { BSL_SAL_FREE(tmpIdentity); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16818, "Dump fail"); } ctx->hsCtx->kxCtx->pskInfo->pskLen = pskUsedLen; if (tmpIdentity != NULL) { BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo->identity); ctx->hsCtx->kxCtx->pskInfo->identity = tmpIdentity; ctx->hsCtx->kxCtx->pskInfo->identityLen = identityUsedLen; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PSK */ uint32_t HS_GetState(const TLS_Ctx *ctx) { if (ctx->hsCtx == NULL) { return HS_STATE_BUTT; } return ctx->hsCtx->state; } #ifdef HITLS_TLS_FEATURE_SNI const char *HS_GetServerName(const TLS_Ctx *ctx) { if (ctx == NULL || ctx->hsCtx == NULL) { return NULL; } return (char *)ctx->hsCtx->serverName; } #endif int32_t HS_GrowMsgBuf(TLS_Ctx *ctx, uint32_t msgSize, bool keepOldData) { if (msgSize <= ctx->hsCtx->bufferLen) { return HITLS_SUCCESS; } uint32_t bufSize = ctx->hsCtx->bufferLen; uint32_t oldDataSize = bufSize; uint8_t *oldDataAddr = ctx->hsCtx->msgBuf; while (bufSize != 0 && bufSize < msgSize) { bufSize = bufSize << 1; } ctx->hsCtx->msgBuf = BSL_SAL_Calloc(1u, bufSize); if (ctx->hsCtx->msgBuf == NULL) { ctx->hsCtx->msgBuf = oldDataAddr; BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15935, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "msgBuf malloc fail while get reass msg.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ctx->hsCtx->bufferLen = bufSize; if (keepOldData) { (void)memcpy_s(ctx->hsCtx->msgBuf, bufSize, oldDataAddr, oldDataSize); } BSL_SAL_FREE(oldDataAddr); return HITLS_SUCCESS; } int32_t HS_ReSizeMsgBuf(TLS_Ctx *ctx, uint32_t msgSize) { bool keepOldData = false; return HS_GrowMsgBuf(ctx, msgSize, keepOldData); } uint32_t HS_MaxMessageSize(TLS_Ctx *ctx, HS_MsgType type) { switch (type) { case HELLO_REQUEST: return HITLS_HELLO_REQUEST_MAX_SIZE; case CLIENT_HELLO: return HITLS_CLIENT_HELLO_MAX_SIZE; #ifdef HITLS_TLS_PROTO_DTLS12 case HELLO_VERIFY_REQUEST: return HITLS_HELLO_VERIFY_REQUEST_MAX_SIZE; #endif case SERVER_HELLO: return HITLS_SERVER_HELLO_MAX_SIZE; case ENCRYPTED_EXTENSIONS: return HITLS_ENCRYPTED_EXTENSIONS_MAX_SIZE; case CERTIFICATE: if (ctx->config.tlsConfig.maxCertList == 0) { return HITLS_MAX_CERT_LIST_DEFAULT; } return ctx->config.tlsConfig.maxCertList; case SERVER_KEY_EXCHANGE: return HITLS_SERVER_KEY_EXCH_MAX_SIZE; case CERTIFICATE_REQUEST: if (ctx->config.tlsConfig.maxCertList == 0) { return HITLS_MAX_CERT_LIST_DEFAULT; } return ctx->config.tlsConfig.maxCertList; case SERVER_HELLO_DONE: return HITLS_SERVER_HELLO_DONE_MAX_SIZE; case CLIENT_KEY_EXCHANGE: return HITLS_CLIENT_KEY_EXCH_MAX_SIZE; case CERTIFICATE_VERIFY: return REC_MAX_PLAIN_LENGTH; case NEW_SESSION_TICKET: if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13) { return HITLS_SESSION_TICKET_MAX_SIZE_TLS13; } return HITLS_SESSION_TICKET_MAX_SIZE_TLS12; case END_OF_EARLY_DATA: return HITLS_END_OF_EARLY_DATA_MAX_SIZE; case FINISHED: return HITLS_FINISHED_MAX_SIZE; case KEY_UPDATE: return HITLS_KEY_UPDATE_MAX_SIZE; default: return 0; } } #ifdef HITLS_TLS_PROTO_TLS13 uint32_t HS_GetBinderLen(HITLS_Session *session, HITLS_HashAlgo *hashAlg) { if (*hashAlg != HITLS_HASH_BUTT) { return SAL_CRYPT_HmacSize(*hashAlg); } if (session == NULL) { return 0; } uint16_t cipherSuite = 0; int32_t ret = HITLS_SESS_GetCipherSuite(session, &cipherSuite); if (ret != HITLS_SUCCESS) { return 0; } CipherSuiteInfo cipherInfo = {0}; ret = CFG_GetCipherSuiteInfo(cipherSuite, &cipherInfo); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16819, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetCipherSuiteInfo fail", 0, 0, 0, 0); return 0; } *hashAlg = cipherInfo.hashAlg; return SAL_CRYPT_HmacSize(*hashAlg); } #endif /* HITLS_TLS_PROTO_TLS13 */ bool GroupConformToVersion(const TLS_Ctx *ctx, uint16_t version, uint16_t group) { uint32_t versionBits = MapVersion2VersionBit(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), version); const TLS_GroupInfo *groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, group); if (groupInfo == NULL || ((groupInfo->versionBits & versionBits) != versionBits)) { return false; } return true; } uint16_t *CheckSupportSignAlgorithms(const TLS_Ctx *ctx, const uint16_t *signAlgorithms, uint32_t signAlgorithmsSize, uint32_t *newSignAlgorithmsSize) { (void)ctx; uint32_t validNum = 0; uint16_t *retSignAlgorithms = BSL_SAL_Calloc(signAlgorithmsSize, sizeof(uint16_t)); if (retSignAlgorithms == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17308, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } for (uint32_t i = 0; i < signAlgorithmsSize; i++) { #ifdef HITLS_TLS_PROTO_TLS13 const uint32_t dsaMask = 0x02; const uint32_t sha1Mask = 0x0200; const uint32_t sha224Mask = 0x0300; if (ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13 && ctx->config.tlsConfig.minVersion == HITLS_VERSION_TLS13) { if (ctx->isClient && (((signAlgorithms[i] & 0xff00) == sha1Mask) || ((signAlgorithms[i] & 0xff00) == sha224Mask))) { continue; } if (((signAlgorithms[i] & 0xff) == dsaMask) || signAlgorithms[i] == CERT_SIG_SCHEME_RSA_PKCS1_SHA1 || signAlgorithms[i] == CERT_SIG_SCHEME_RSA_PKCS1_SHA224) { continue; } } #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_FEATURE_SECURITY if (SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_SIGALG_CHECK, 0, signAlgorithms[i], NULL) != SECURITY_SUCCESS) { continue; } #endif /* HITLS_TLS_FEATURE_SECURITY */ retSignAlgorithms[validNum] = signAlgorithms[i]; validNum++; } *newSignAlgorithmsSize = validNum; return retSignAlgorithms; } uint32_t HS_GetExtensionTypeId(uint32_t hsExtensionsType) { switch (hsExtensionsType) { case HS_EX_TYPE_SERVER_NAME: return HS_EX_TYPE_ID_SERVER_NAME; case HS_EX_TYPE_SUPPORTED_GROUPS: return HS_EX_TYPE_ID_SUPPORTED_GROUPS; case HS_EX_TYPE_POINT_FORMATS: return HS_EX_TYPE_ID_POINT_FORMATS; case HS_EX_TYPE_SIGNATURE_ALGORITHMS: return HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS; case HS_EX_TYPE_APP_LAYER_PROTOCOLS: return HS_EX_TYPE_ID_APP_LAYER_PROTOCOLS; case HS_EX_TYPE_ENCRYPT_THEN_MAC: return HS_EX_TYPE_ID_ENCRYPT_THEN_MAC; case HS_EX_TYPE_EXTENDED_MASTER_SECRET: return HS_EX_TYPE_ID_EXTENDED_MASTER_SECRET; case HS_EX_TYPE_SESSION_TICKET: return HS_EX_TYPE_ID_SESSION_TICKET; case HS_EX_TYPE_PRE_SHARED_KEY: return HS_EX_TYPE_ID_PRE_SHARED_KEY; case HS_EX_TYPE_SUPPORTED_VERSIONS: return HS_EX_TYPE_ID_SUPPORTED_VERSIONS; case HS_EX_TYPE_COOKIE: return HS_EX_TYPE_ID_COOKIE; case HS_EX_TYPE_PSK_KEY_EXCHANGE_MODES: return HS_EX_TYPE_ID_PSK_KEY_EXCHANGE_MODES; case HS_EX_TYPE_CERTIFICATE_AUTHORITIES: return HS_EX_TYPE_ID_CERTIFICATE_AUTHORITIES; case HS_EX_TYPE_POST_HS_AUTH: return HS_EX_TYPE_ID_POST_HS_AUTH; case HS_EX_TYPE_KEY_SHARE: return HS_EX_TYPE_ID_KEY_SHARE; case HS_EX_TYPE_RENEGOTIATION_INFO: return HS_EX_TYPE_ID_RENEGOTIATION_INFO; default: break; } return HS_EX_TYPE_ID_UNRECOGNIZED; } int32_t HS_CheckReceivedExtension(HITLS_Ctx *ctx, HS_MsgType hsType, uint64_t hsMsgExtensionsMask, uint64_t hsMsgAllowedExtensionsMask) { if ((hsMsgExtensionsMask & hsMsgAllowedExtensionsMask) != hsMsgExtensionsMask) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17311, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "%d msg have illegal extensions, extensionMask: %lu", hsType, hsMsgExtensionsMask, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } return HITLS_SUCCESS; } bool IsCipherSuiteAllowed(const HITLS_Ctx *ctx, uint16_t cipherSuite) { if (!CFG_CheckCipherSuiteSupported(cipherSuite)) { return false; } uint16_t minVersion = ctx->config.tlsConfig.minVersion; uint16_t maxVersion = ctx->config.tlsConfig.maxVersion; if (!CFG_CheckCipherSuiteVersion(cipherSuite, minVersion, maxVersion)) { return false; } CipherSuiteInfo cipherInfo = {0}; (void)CFG_GetCipherSuiteInfo(cipherSuite, &cipherInfo); if ((ctx->isClient && ctx->config.tlsConfig.pskClientCb == NULL) || (!ctx->isClient && ctx->config.tlsConfig.pskServerCb == NULL)) { if ((cipherInfo.kxAlg == HITLS_KEY_EXCH_PSK) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_DHE_PSK) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_ECDHE_PSK) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_RSA_PSK)) { return false; } } uint16_t negotiatedVersion = ctx->negotiatedInfo.version; if (negotiatedVersion > 0) { if (!CFG_CheckCipherSuiteVersion(cipherSuite, negotiatedVersion, negotiatedVersion)) { return false; } } return true; }
2301_79861745/bench_create
tls/handshake/common/src/hs_common.c
C
unknown
30,583
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_uio.h" #include "bsl_errno.h" #include "sal_time.h" #include "hitls.h" #include "hitls_error.h" #include "tls_config.h" #include "hs_ctx.h" #include "hs_dtls_timer.h" #define DTLS_HS_2MSL_TIMEOUT_VALUE 240000000 /* 2 times the MSL(Maximum Segment Lifetime) time. Unit: us */ #define DTLS_HS_DEFAULT_TIMEOUT_VALUE 1000000 #define DTLS_HS_MAX_TIMEOUT_VALUE 60000000 #define DTLS_HS_MAX_TIMEOUT_NUM 12 /* Maximum Timeout Times */ #define DTLS_IP_MIN_MTU 548 /* ipv4 min mtu is 576, ipv4 protocol header 20, udp header 8, it needs subtraction here */ #define NEED_REDUCE_MTU_TIMEOUT_NUM 2 static int32_t SetDtlsTimerDeadLine(TLS_Ctx *ctx, uint32_t timeoutValue) { HS_Ctx *hsCtx = ctx->hsCtx; BSL_TIME curTime = {0}; int32_t ret = (int32_t)BSL_SAL_SysTimeGet(&curTime); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_SYS_TIME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15774, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "BSL_SAL_SysTimeGet fail when start dtls timer.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_SYS_TIME_FAIL; } ret = (int32_t)BSL_DateTimeAddUs(&hsCtx->deadline, &curTime, timeoutValue); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_SYS_TIME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15775, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "BSL_DateTimeAddUs fail when start dtls timer.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_SYS_TIME_FAIL; } return HITLS_SUCCESS; } int32_t HS_Start2MslTimer(TLS_Ctx *ctx) { HS_Ctx *hsCtx = ctx->hsCtx; if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } uint32_t timeoutValue = DTLS_HS_2MSL_TIMEOUT_VALUE; if (ctx->config.tlsConfig.dtlsPostHsTimeoutVal != 0) { timeoutValue = ctx->config.tlsConfig.dtlsPostHsTimeoutVal; } int32_t ret = SetDtlsTimerDeadLine(ctx, timeoutValue); if (ret != BSL_SUCCESS) { return ret; } hsCtx->timeoutValue = timeoutValue; hsCtx->timeoutNum = 0; return HITLS_SUCCESS; } int32_t HS_StartTimer(TLS_Ctx *ctx) { HS_Ctx *hsCtx = ctx->hsCtx; if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } uint32_t timeoutValue = DTLS_HS_DEFAULT_TIMEOUT_VALUE; if (ctx->config.tlsConfig.dtlsTimerCb != NULL) { timeoutValue = ctx->config.tlsConfig.dtlsTimerCb(ctx, 0); } int32_t ret = SetDtlsTimerDeadLine(ctx, timeoutValue); if (ret != BSL_SUCCESS) { return ret; } hsCtx->timeoutValue = timeoutValue; hsCtx->timeoutNum = 0; return HITLS_SUCCESS; } int32_t HS_IsTimeout(TLS_Ctx *ctx, bool *isTimeout) { HS_Ctx *hsCtx = ctx->hsCtx; if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { *isTimeout = false; return HITLS_SUCCESS; } BSL_TIME curTime = {0}; int32_t ret = (int32_t)BSL_SAL_SysTimeGet(&curTime); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_SYS_TIME_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15776, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "BSL_SAL_SysTimeGet fail when judgment dtls timeout.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_SYS_TIME_FAIL; } *isTimeout = false; /* When the server sends the hello verify request, the timer does not need to be started. In this case, the function * returns a failure. Therefore, the failure is not considered as timeout */ ret = (int32_t)BSL_SAL_DateTimeCompareByUs(&curTime, &hsCtx->deadline); if (ret == BSL_TIME_DATE_AFTER) { *isTimeout = true; } return HITLS_SUCCESS; } int32_t HS_TimeoutProcess(TLS_Ctx *ctx) { HS_Ctx *hsCtx = ctx->hsCtx; if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15777, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "dtls timeout, timeoutNum = %u, timeoutValue = %u(us).", hsCtx->timeoutNum, hsCtx->timeoutValue, 0, 0); uint32_t timeoutValue = hsCtx->timeoutValue; if (ctx->config.tlsConfig.dtlsTimerCb != NULL) { timeoutValue = ctx->config.tlsConfig.dtlsTimerCb(ctx, timeoutValue); } else { timeoutValue *= 2; /* 2 indicates that the timeout period for each retransmission is doubled. */ if (timeoutValue > DTLS_HS_MAX_TIMEOUT_VALUE) { /* The maximum timeout duration of the timer is 60s */ timeoutValue = DTLS_HS_MAX_TIMEOUT_VALUE; } } int32_t ret = SetDtlsTimerDeadLine(ctx, timeoutValue); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16827, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SetDtlsTimerDeadLine fail", 0, 0, 0, 0); return ret; } hsCtx->timeoutValue = timeoutValue; hsCtx->timeoutNum++; if (hsCtx->timeoutNum > NEED_REDUCE_MTU_TIMEOUT_NUM && !ctx->noQueryMtu) { if (ctx->config.pmtu > DTLS_IP_MIN_MTU) { ctx->config.pmtu = DTLS_IP_MIN_MTU; ctx->mtuModified = true; } } if (hsCtx->timeoutNum > DTLS_HS_MAX_TIMEOUT_NUM) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_DTLS_CONNECT_TIMEOUT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15778, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dtls connect timeout.", 0, 0, 0, 0); /* There is no need to send an alert to peer after multiple connection failures */ return HITLS_MSG_HANDLE_DTLS_CONNECT_TIMEOUT; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
2301_79861745/bench_create
tls/handshake/common/src/hs_dtls_timer.c
C
unknown
6,617
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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" #include "securec.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 "bsl_sal.h" #include "hitls_error.h" #include "hitls_security.h" #include "crypt.h" #include "cert_method.h" #include "session.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "hs_ctx.h" #include "transcript_hash.h" #include "hs_common.h" #include "hs_kx.h" KeyExchCtx *HS_KeyExchCtxNew(void) { KeyExchCtx *keyExchCtx = (KeyExchCtx *)BSL_SAL_Malloc(sizeof(KeyExchCtx)); if (keyExchCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15514, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "keyExchCtx malloc failed.", 0, 0, 0, 0); return NULL; } (void)memset_s(keyExchCtx, sizeof(KeyExchCtx), 0, sizeof(KeyExchCtx)); return keyExchCtx; } void HS_KeyExchCtxFree(KeyExchCtx *keyExchCtx) { if (keyExchCtx == NULL) { return; } #ifdef HITLS_TLS_FEATURE_PSK if (keyExchCtx->pskInfo != NULL) { BSL_SAL_CleanseData(keyExchCtx->pskInfo->psk, keyExchCtx->pskInfo->pskLen); BSL_SAL_FREE(keyExchCtx->pskInfo->identity); BSL_SAL_FREE(keyExchCtx->pskInfo->psk); BSL_SAL_FREE(keyExchCtx->pskInfo); } #endif /* HITLS_TLS_FEATURE_PSK */ #ifdef HITLS_TLS_PROTO_TLS13 BSL_SAL_CleanseData(keyExchCtx->pskInfo13.psk, keyExchCtx->pskInfo13.pskLen); BSL_SAL_FREE(keyExchCtx->pskInfo13.psk); HITLS_SESS_Free(keyExchCtx->pskInfo13.resumeSession); keyExchCtx->pskInfo13.resumeSession = NULL; if (keyExchCtx->pskInfo13.userPskSess != NULL) { HITLS_SESS_Free(keyExchCtx->pskInfo13.userPskSess->pskSession); keyExchCtx->pskInfo13.userPskSess->pskSession = NULL; BSL_SAL_FREE(keyExchCtx->pskInfo13.userPskSess->identity); BSL_SAL_FREE(keyExchCtx->pskInfo13.userPskSess); } BSL_SAL_FREE(keyExchCtx->ciphertext); #endif /* HITLS_TLS_PROTO_TLS13 */ BSL_SAL_FREE(keyExchCtx->peerPubkey); SAL_CRYPT_FreeEcdhKey(keyExchCtx->secondKey); switch (keyExchCtx->keyExchAlgo) { case HITLS_KEY_EXCH_NULL: case HITLS_KEY_EXCH_ECDHE: case HITLS_KEY_EXCH_ECDH: case HITLS_KEY_EXCH_ECDHE_PSK: SAL_CRYPT_FreeEcdhKey(keyExchCtx->key); break; case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: case HITLS_KEY_EXCH_DH: SAL_CRYPT_FreeDhKey(keyExchCtx->key); BSL_SAL_FREE(keyExchCtx->keyExchParam.dh.p); BSL_SAL_FREE(keyExchCtx->keyExchParam.dh.g); break; case HITLS_KEY_EXCH_RSA: default: break; } BSL_SAL_FREE(keyExchCtx); return; } #ifdef HITLS_TLS_HOST_CLIENT #ifdef HITLS_TLS_SUITE_KX_ECDHE static bool NamedCurveSupport(HITLS_NamedGroup inNamedGroup, const TLS_Config *config) { for (uint32_t i = 0u; i < config->groupsSize; i++) { if (inNamedGroup == config->groups[i]) { return true; } } return false; } static int32_t ProcessServerKxMsgNamedCurve(TLS_Ctx *ctx, const ServerKeyExchangeMsg *serverKxMsg) { HITLS_ECCurveType type = serverKxMsg->keyEx.ecdh.ecPara.type; HITLS_NamedGroup namedGroup = serverKxMsg->keyEx.ecdh.ecPara.param.namedcurve; if (NamedCurveSupport(namedGroup, &ctx->config.tlsConfig) == false) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_NAMED_CURVE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15515, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "no supported curves found.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_UNSUPPORT_NAMED_CURVE; } uint32_t peerPubkeyLen = serverKxMsg->keyEx.ecdh.pubKeySize; uint8_t *peerPubkey = BSL_SAL_Malloc(peerPubkeyLen); if (peerPubkey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15516, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pubkey malloc fail when process server kx msg named curve.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(peerPubkey, peerPubkeyLen, serverKxMsg->keyEx.ecdh.pubKey, peerPubkeyLen); ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type = type; ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.param.namedcurve = namedGroup; HITLS_CRYPT_Key *key = SAL_CRYPT_GenEcdhKeyPair(ctx, &ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams); if (key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15517, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get ecdh key pair fail when process server kx msg named curve.", 0, 0, 0, 0); BSL_SAL_FREE(peerPubkey); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_ERR_ENCODE_ECDH_KEY; } ctx->hsCtx->kxCtx->key = key; ctx->hsCtx->kxCtx->peerPubkey = peerPubkey; ctx->hsCtx->kxCtx->pubKeyLen = peerPubkeyLen; ctx->negotiatedInfo.negotiatedGroup = namedGroup; return HITLS_SUCCESS; } int32_t HS_ProcessServerKxMsgEcdhe(TLS_Ctx *ctx, const ServerKeyExchangeMsg *serverKxMsg) { HITLS_ECCurveType type = serverKxMsg->keyEx.ecdh.ecPara.type; switch (type) { case HITLS_EC_CURVE_TYPE_NAMED_CURVE: return ProcessServerKxMsgNamedCurve(ctx, serverKxMsg); default: break; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNKNOWN_CURVE_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15518, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unknow the curve type in server kx msg.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_UNKNOWN_CURVE_TYPE; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE int32_t HS_ProcessServerKxMsgDhe(TLS_Ctx *ctx, const ServerKeyExchangeMsg *serverKxMsg) { const ServerDh *dh = &serverKxMsg->keyEx.dh; HITLS_CRYPT_Key *key = SAL_CRYPT_GenerateDhKeyByParams(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), dh->p, dh->plen, dh->g, dh->glen); if (key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_ENCODE_DH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15519, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get dhe key pair fail when process server dhe kx msg.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_ERR_ENCODE_DH_KEY; } uint8_t *pubkey = BSL_SAL_Dump(dh->pubkey, dh->pubKeyLen); if (pubkey == NULL) { SAL_CRYPT_FreeDhKey(key); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15520, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pubkey malloc fail when process server dhe kx msg.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ctx->hsCtx->kxCtx->keyExchParam.dh.plen = dh->plen; ctx->hsCtx->kxCtx->key = key; ctx->hsCtx->kxCtx->peerPubkey = pubkey; ctx->hsCtx->kxCtx->pubKeyLen = dh->pubKeyLen; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_DHE */ #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER #ifdef HITLS_TLS_SUITE_KX_ECDHE static int32_t ProcessClientKxMsgNamedCurve(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg) { uint32_t peerPubkeyLen = clientKxMsg->dataSize; uint8_t *peerPubkey = BSL_SAL_Malloc(peerPubkeyLen); if (peerPubkey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15521, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pubkey malloc fail when process client kx msg named curve.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(peerPubkey, peerPubkeyLen, clientKxMsg->data, peerPubkeyLen); ctx->hsCtx->kxCtx->peerPubkey = peerPubkey; ctx->hsCtx->kxCtx->pubKeyLen = peerPubkeyLen; return HITLS_SUCCESS; } int32_t HS_ProcessClientKxMsgEcdhe(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg) { HITLS_ECCurveType type = ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type; switch (type) { case HITLS_EC_CURVE_TYPE_NAMED_CURVE: return ProcessClientKxMsgNamedCurve(ctx, clientKxMsg); default: break; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNKNOWN_CURVE_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15522, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unknow the curve type in client kx msg.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_UNKNOWN_CURVE_TYPE; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE int32_t HS_ProcessClientKxMsgDhe(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg) { uint32_t peerPubkeyLen = clientKxMsg->dataSize; uint8_t *peerPubkey = BSL_SAL_Dump(clientKxMsg->data, peerPubkeyLen); if (peerPubkey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15523, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pubkey malloc fail when process client dhe kx msg.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ctx->hsCtx->kxCtx->peerPubkey = peerPubkey; ctx->hsCtx->kxCtx->pubKeyLen = peerPubkeyLen; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_RSA int32_t HS_ProcessClientKxMsgRsa(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; KeyExchCtx *keyExchCtx = hsCtx->kxCtx; uint32_t secretLen = clientKxMsg->dataSize < MASTER_SECRET_LEN ? MASTER_SECRET_LEN : clientKxMsg->dataSize; uint8_t *premasterSecret = BSL_SAL_Calloc(1u, secretLen); if (premasterSecret == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15524, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Decrypt RSA-Encrypted Premaster Secret error: out of memory.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } uint8_t premaster[MASTER_SECRET_LEN]; ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), premaster, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(premasterSecret); return ret; } CERT_MgrCtx *certMgrCtx = ctx->config.tlsConfig.certMgrCtx; HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(certMgrCtx, false); uint32_t valid = ~(uint32_t)SAL_CERT_KeyDecrypt(ctx, privateKey, clientKxMsg->data, clientKxMsg->dataSize, premasterSecret, &secretLen); valid &= Uint32ConstTimeEqual(secretLen, MASTER_SECRET_LEN); // Check the version in the premaster secret uint16_t version = ctx->negotiatedInfo.clientVersion; uint32_t versionCheck = Uint32ConstTimeEqual(version, HITLS_VERSION_TLS11) | Uint32ConstTimeEqual(version, HITLS_VERSION_TLS12) | Uint32ConstTimeEqual(version, HITLS_VERSION_DTLS12) | ~Uint32ConstTimeIsZero((uint32_t)ctx->config.tlsConfig.needCheckPmsVersion); valid &= (~versionCheck) | Uint32ConstTimeEqual(version, BSL_ByteToUint16(premasterSecret)); for (uint32_t i = 0; i < MASTER_SECRET_LEN; i++) { uint32_t mask = valid & Uint32ConstTimeLt(i, secretLen); keyExchCtx->keyExchParam.rsa.preMasterSecret[i] = Uint8ConstTimeSelect(mask, premasterSecret[i & mask], premaster[i]); } BSL_SAL_CleanseData(premasterSecret, secretLen); BSL_SAL_FREE(premasterSecret); return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_PROTO_TLCP11 int32_t HS_ProcessClientKxMsgSm2(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; KeyExchCtx *keyExchCtx = hsCtx->kxCtx; uint8_t *preMasterSecret = BSL_SAL_Calloc(1u, clientKxMsg->dataSize); if (preMasterSecret == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16213, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Decrypt SM2-Encrypted PremasterSecret error: out of memory", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } uint32_t secretLen = clientKxMsg->dataSize; CERT_MgrCtx *certMgrCtx = ctx->config.tlsConfig.certMgrCtx; HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(certMgrCtx, true); ret = SAL_CERT_KeyDecrypt(ctx, privateKey, clientKxMsg->data, clientKxMsg->dataSize, preMasterSecret, &secretLen); if ((ret != HITLS_SUCCESS) || (secretLen != MASTER_SECRET_LEN)) { /* If the server fails to process the message, it is prohibited to send the alert message. The randomly * generated premaster secret must be used to continue the handshake */ SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), keyExchCtx->keyExchParam.ecc.preMasterSecret, MASTER_SECRET_LEN); BSL_SAL_FREE(preMasterSecret); return HITLS_SUCCESS; } uint16_t clientVersion = BSL_ByteToUint16(preMasterSecret); // In any case, a TLS server MUST NOT generate an alert if processing an RSA-encrypted // premaster secret message fails, or the version number is not as expected. if (ctx->negotiatedInfo.clientVersion != clientVersion) { // If the version does not match, a 46-byte preMasterSecret is randomly generated uint16_t version = ctx->negotiatedInfo.clientVersion; uint32_t offset = 0u; // 8:right shift a byte keyExchCtx->keyExchParam.ecc.preMasterSecret[offset++] = (uint8_t)(version >> 8); keyExchCtx->keyExchParam.ecc.preMasterSecret[offset++] = (uint8_t)(version); SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), keyExchCtx->keyExchParam.ecc.preMasterSecret + offset, MASTER_SECRET_LEN - offset); BSL_SAL_CleanseData(preMasterSecret, secretLen); BSL_SAL_FREE(preMasterSecret); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15348, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Parse RSA-Encrypted Premaster Secret client version mismatch: msg clientVersion = %u, \ ctx->negotiatedInfo.clientVersion = %u.", clientVersion, ctx->negotiatedInfo.clientVersion, 0, 0); return HITLS_SUCCESS; } (void)memcpy_s(keyExchCtx->keyExchParam.ecc.preMasterSecret, MASTER_SECRET_LEN, preMasterSecret, secretLen); BSL_SAL_CleanseData(preMasterSecret, secretLen); BSL_SAL_FREE(preMasterSecret); return HITLS_SUCCESS; } #endif #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_FEATURE_PSK static int32_t AppendPsk(uint8_t *pskPmsBuf, uint32_t pskPmsBufLen, uint8_t *psk, uint32_t pskLen) { uint32_t offset = 0u; uint8_t *pskPmsBufTmp = pskPmsBuf; BSL_Uint16ToByte((uint16_t)pskLen, pskPmsBufTmp); offset += sizeof(uint16_t); if (memcpy_s(&pskPmsBufTmp[offset], pskPmsBufLen - offset, psk, pskLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16828, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } static int32_t GeneratePskPreMasterSecret(TLS_Ctx *ctx, uint8_t *pmsBuf, uint32_t pmsBufLen, uint32_t *pmsUsedLen) { int32_t ret = HITLS_SUCCESS; uint32_t offset = 0u; uint8_t tmpPskPmsBufTmp[MAX_PRE_MASTER_SECRET_SIZE] = {0}; uint8_t *psk = ctx->hsCtx->kxCtx->pskInfo->psk; uint32_t pskLen = ctx->hsCtx->kxCtx->pskInfo->pskLen; if (psk == NULL || pskLen > HS_PSK_MAX_LEN) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID16829, "input null"); } switch (ctx->hsCtx->kxCtx->keyExchAlgo) { /* |shareKeyLen(2 byte)|shareKey|PskLen(2 byte)|psk| */ case HITLS_KEY_EXCH_DHE_PSK: case HITLS_KEY_EXCH_ECDHE_PSK: /* Padding ShareKeyLen */ BSL_Uint16ToByte((uint16_t)*pmsUsedLen, &tmpPskPmsBufTmp[offset]); offset += sizeof(uint16_t); /* Padding ShareKey */ ret = memcpy_s(&tmpPskPmsBufTmp[offset], MAX_PRE_MASTER_SECRET_SIZE - offset, pmsBuf, *pmsUsedLen); offset += *pmsUsedLen; break; /* |48(2 byte)|version number(2 byte)|rand value(46 byte)|pskLen(2 byte)|psk| */ case HITLS_KEY_EXCH_RSA_PSK: /* Padding the length (Version + RandValue). The value is fixed to 48 */ BSL_Uint16ToByte(MASTER_SECRET_LEN, &tmpPskPmsBufTmp[offset]); offset = sizeof(uint16_t); /* Padding |Version|RandValue| */ ret = memcpy_s(&tmpPskPmsBufTmp[offset], MAX_PRE_MASTER_SECRET_SIZE - offset, pmsBuf, *pmsUsedLen); offset += MASTER_SECRET_LEN; break; /* |N(2 byte)|N 0s|N(2 byte)|psk|, N stands for pskLen */ case HITLS_KEY_EXCH_PSK: /* Padding pskLen */ BSL_Uint16ToByte((uint16_t)pskLen, &tmpPskPmsBufTmp[offset]); offset = sizeof(uint16_t); /* padding pskLen with zeros */ ret = memset_s(&tmpPskPmsBufTmp[offset], MAX_PRE_MASTER_SECRET_SIZE - offset, 0, pskLen); offset += pskLen; break; default: /* no key exchange algo matched */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG, BINLOG_ID16830, "unknow keyExchAlgo"); } if (ret != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16831, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "key exchange algo is %d, memcpy fail", ctx->hsCtx->kxCtx->keyExchAlgo, 0, 0, 0); goto ERR; } if (AppendPsk(&tmpPskPmsBufTmp[offset], MAX_PRE_MASTER_SECRET_SIZE - offset, psk, pskLen) != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16832, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "AppendPsk fail", 0, 0, 0, 0); goto ERR; } offset += (sizeof(uint16_t) + pskLen); if (memcpy_s(pmsBuf, pmsBufLen, tmpPskPmsBufTmp, offset) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16833, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); goto ERR; } *pmsUsedLen = offset; (void)memset_s(tmpPskPmsBufTmp, MAX_PRE_MASTER_SECRET_SIZE, 0, MAX_PRE_MASTER_SECRET_SIZE); return HITLS_SUCCESS; ERR: (void)memset_s(tmpPskPmsBufTmp, MAX_PRE_MASTER_SECRET_SIZE, 0, MAX_PRE_MASTER_SECRET_SIZE); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } #endif /* HITLS_TLS_FEATURE_PSK */ int32_t DeriveMasterSecret(TLS_Ctx *ctx, const uint8_t *preMasterSecret, uint32_t len) { int32_t ret = HITLS_SUCCESS; const uint8_t masterSecretLabel[] = "master secret"; const uint8_t exMasterSecretLabel[] = "extended master secret"; uint8_t seed[HS_RANDOM_SIZE * 2] = {0}; // seed size is twice the random size uint32_t seedLen = sizeof(seed); bool isExtendedMasterSecret = ctx->negotiatedInfo.isExtendedMasterSecret; CRYPT_KeyDeriveParameters deriveInfo; deriveInfo.hashAlgo = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; deriveInfo.secret = preMasterSecret; deriveInfo.secretLen = len; if (isExtendedMasterSecret) { deriveInfo.label = exMasterSecretLabel; deriveInfo.labelLen = sizeof(exMasterSecretLabel) - 1u; ret = VERIFY_CalcSessionHash( ctx->hsCtx->verifyCtx, seed, &seedLen); // Use session hash as seed for key deriviation } else { deriveInfo.label = masterSecretLabel; deriveInfo.labelLen = sizeof(masterSecretLabel) - 1u; ret = HS_CombineRandom(ctx->hsCtx->clientRandom, ctx->hsCtx->serverRandom, HS_RANDOM_SIZE, seed, seedLen); } if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15525, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get PRF seed fail.", 0, 0, 0, 0); return ret; } deriveInfo.seed = seed; deriveInfo.seedLen = seedLen; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); ret = SAL_CRYPT_PRF(&deriveInfo, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15526, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "failed to invoke the PRF function.", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_MAINTAIN_KEYLOG if (HITLS_LogSecret(ctx, MASTER_SECRET_LABEL, ctx->hsCtx->masterKey, MASTER_SECRET_LEN) != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15336, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "failed to LogSecret, MASTER_SECRET_LABEL.", 0, 0, 0, 0); } #endif /* HITLS_TLS_MAINTAIN_KEYLOG */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_SUITE_KX_ECDHE static int32_t GenPremasterSecretFromEcdhe(TLS_Ctx *ctx, uint8_t *preMasterSecret, uint32_t *preMasterSecretLen) { #ifdef HITLS_TLS_PROTO_TLCP11 int32_t ret = HITLS_SUCCESS; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *certMgrCtx = config->certMgrCtx; HITLS_CERT_Key *priKey = SAL_CERT_GetCurrentPrivateKey(certMgrCtx, true); if (priKey == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16834, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetCurrentPrivateKey fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_EXP_CERT); return HITLS_CERT_ERR_EXP_CERT; } HITLS_CRYPT_Key *peerPubKey = NULL; HITLS_CERT_X509 *cert = SAL_CERT_GetTlcpEncCert(ctx->hsCtx->peerCert); ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&peerPubKey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16835, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GET_PUB_KEY fail", 0, 0, 0, 0); return ret; } *preMasterSecretLen = MASTER_SECRET_LEN; HITLS_Sm2GenShareKeyParameters sm2ShareKeyParam = {ctx->hsCtx->kxCtx->key, ctx->hsCtx->kxCtx->peerPubkey, ctx->hsCtx->kxCtx->pubKeyLen, priKey, peerPubKey, ctx->isClient }; ret = SAL_CRYPT_CalcSm2dhSharedSecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &sm2ShareKeyParam, preMasterSecret, preMasterSecretLen); SAL_CERT_KeyFree(certMgrCtx, peerPubKey); return ret; } #endif return SAL_CRYPT_CalcEcdhSharedSecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), ctx->hsCtx->kxCtx->key, ctx->hsCtx->kxCtx->peerPubkey, ctx->hsCtx->kxCtx->pubKeyLen, preMasterSecret, preMasterSecretLen); } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ static int32_t GenPreMasterSecret(TLS_Ctx *ctx, uint8_t *preMasterSecret, uint32_t *preMasterSecretLen) { int32_t ret = HITLS_SUCCESS; KeyExchCtx *keyExchCtx = ctx->hsCtx->kxCtx; (void)preMasterSecret; (void)preMasterSecretLen; switch (keyExchCtx->keyExchAlgo) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: case HITLS_KEY_EXCH_ECDHE_PSK: ret = GenPremasterSecretFromEcdhe(ctx, preMasterSecret, preMasterSecretLen); break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = SAL_CRYPT_CalcDhSharedSecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), keyExchCtx->key, keyExchCtx->peerPubkey, keyExchCtx->pubKeyLen, preMasterSecret, preMasterSecretLen); break; #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_RSA case HITLS_KEY_EXCH_RSA: case HITLS_KEY_EXCH_RSA_PSK: if (memcpy_s(preMasterSecret, *preMasterSecretLen, keyExchCtx->keyExchParam.rsa.preMasterSecret, MASTER_SECRET_LEN) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID16836, "memcpy fail"); } *preMasterSecretLen = MASTER_SECRET_LEN; break; #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: if (memcpy_s(preMasterSecret, *preMasterSecretLen, keyExchCtx->keyExchParam.ecc.preMasterSecret, MASTER_SECRET_LEN) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID16837, "memcpy fail"); } *preMasterSecretLen = MASTER_SECRET_LEN; break; #endif case HITLS_KEY_EXCH_PSK: break; default: BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG, BINLOG_ID16838, "unknow keyExchAlgo"); } BSL_ERR_PUSH_ERROR(ret); return ret; } int32_t HS_GenerateMasterSecret(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; uint8_t preMasterSecret[MAX_PRE_MASTER_SECRET_SIZE] = {0}; /* key exchange algorithm contains psk, preMasterSecret: |uint16_t|MAX_OTHER_SECRET_SIZE|uint16_t|HS_PSK_MAX_LEN| key exchange algorithm not contains psk, preMasterSecret: |MAX_OTHER_SECRET_SIZE| */ uint32_t preMasterSecretLen = MAX_OTHER_SECRET_SIZE; ret = GenPreMasterSecret(ctx, preMasterSecret, &preMasterSecretLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15527, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "calc ecdh shared secret failed.", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_FEATURE_PSK /* re-arrange preMasterSecret for psk negotiation */ if (IsPskNegotiation(ctx)) { ret = GeneratePskPreMasterSecret(ctx, preMasterSecret, MAX_PRE_MASTER_SECRET_SIZE, &preMasterSecretLen); if (ret != HITLS_SUCCESS) { BSL_SAL_CleanseData(preMasterSecret, MAX_PRE_MASTER_SECRET_SIZE); BSL_ERR_PUSH_ERROR(ret); return ret; } } #endif /* HITLS_TLS_FEATURE_PSK */ ret = DeriveMasterSecret(ctx, preMasterSecret, preMasterSecretLen); BSL_SAL_CleanseData(preMasterSecret, MAX_PRE_MASTER_SECRET_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15528, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "derive master secret failed.", 0, 0, 0, 0); } return ret; } int32_t HS_SetInitPendingStateParam(const TLS_Ctx *ctx, bool isClient, REC_SecParameters *keyPara) { const HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; const CipherSuiteInfo *cipherSuiteInfo = &ctx->negotiatedInfo.cipherSuiteInfo; keyPara->isClient = isClient; keyPara->prfAlg = cipherSuiteInfo->hashAlg; keyPara->macAlg = cipherSuiteInfo->macAlg; keyPara->cipherAlg = cipherSuiteInfo->cipherAlg; keyPara->cipherType = cipherSuiteInfo->cipherType; keyPara->fixedIvLength = cipherSuiteInfo->fixedIvLength; /** iv length. In the TLS1.2 AEAD algorithm, iv length is the implicit IV length. */ keyPara->encKeyLen = cipherSuiteInfo->encKeyLen; keyPara->macKeyLen = cipherSuiteInfo->macKeyLen; /** If the AEAD algorithm is used, the MAC key length is zero. */ keyPara->blockLength = cipherSuiteInfo->blockLength; keyPara->recordIvLength = cipherSuiteInfo->recordIvLength; /** The explicit IV needs to be sent to the peer. */ keyPara->macLen = cipherSuiteInfo->macLen; if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { uint32_t clientRandomSize = HS_RANDOM_SIZE; if (memcpy_s(keyPara->clientRandom, clientRandomSize, hsCtx->clientRandom, HS_RANDOM_SIZE) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16114, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Client random value copy failed.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } uint32_t serverRandomSize = HS_RANDOM_SIZE; if (memcpy_s(keyPara->serverRandom, serverRandomSize, hsCtx->serverRandom, HS_RANDOM_SIZE) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16115, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Server random value copy failed.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } } return HITLS_SUCCESS; } int32_t HS_KeyEstablish(TLS_Ctx *ctx, bool isClient) { int32_t ret = HITLS_SUCCESS; REC_SecParameters keyPara; uint32_t masterSecretSize = MASTER_SECRET_LEN; ret = HS_SetInitPendingStateParam(ctx, isClient, &keyPara); if (ret != HITLS_SUCCESS) { return ret; } (void)memcpy_s(keyPara.masterSecret, masterSecretSize, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); ret = REC_InitPendingState(ctx, &keyPara); (void)memset_s(keyPara.masterSecret, MASTER_SECRET_LEN, 0, MASTER_SECRET_LEN); return ret; } #ifdef HITLS_TLS_FEATURE_SESSION int32_t HS_ResumeKeyEstablish(TLS_Ctx *ctx) { HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; uint32_t masterKeySize = MAX_DIGEST_SIZE; int32_t ret = HITLS_SESS_GetMasterKey(ctx->session, hsCtx->masterKey, &masterKeySize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15529, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Resume session: get master secret failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ret = HS_KeyEstablish(ctx, ctx->isClient); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15530, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server key establish fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) ret = HS_SetSctpAuthKey(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16839, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "SetSctpAuthKey fail", 0, 0, 0, 0); } #endif return ret; } #endif /* HITLS_TLS_FEATURE_SESSION */ #ifdef HITLS_TLS_FEATURE_PSK int32_t HS_ProcessServerKxMsgIdentityHint(TLS_Ctx *ctx, const ServerKeyExchangeMsg *serverKxMsg) { if (ctx == NULL || serverKxMsg == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16840, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_NULL_INPUT; } uint8_t psk[HS_PSK_MAX_LEN] = {0}; uint8_t identity[HS_PSK_IDENTITY_MAX_LEN + 1] = {0}; int32_t ret = HITLS_SUCCESS; do { if (ctx->config.tlsConfig.pskClientCb == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16841, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pskClientCb null", 0, 0, 0, 0); ret = HITLS_UNREGISTERED_CALLBACK; break; } uint32_t pskUsedLen = ctx->config.tlsConfig.pskClientCb(ctx, serverKxMsg->pskIdentityHint, identity, HS_PSK_IDENTITY_MAX_LEN, psk, HS_PSK_MAX_LEN); if (pskUsedLen == 0 || pskUsedLen > HS_PSK_MAX_LEN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16842, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "psk len err", 0, 0, 0, 0); ret = HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN; break; } uint32_t identityUsedLen = (uint32_t)strnlen((char *)identity, HS_PSK_IDENTITY_MAX_LEN + 1); if (identityUsedLen > HS_PSK_IDENTITY_MAX_LEN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16843, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "identity len err", 0, 0, 0, 0); ret = HITLS_MSG_HANDLE_ILLEGAL_IDENTITY_LEN; break; } if (ctx->hsCtx->kxCtx->pskInfo == NULL) { ctx->hsCtx->kxCtx->pskInfo = (PskInfo *)BSL_SAL_Calloc(1u, sizeof(PskInfo)); if (ctx->hsCtx->kxCtx->pskInfo == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16844, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); ret = HITLS_MEMALLOC_FAIL; break; } } uint8_t *tmpIdentity = (uint8_t *)BSL_SAL_Calloc(1u, (identityUsedLen + 1) * sizeof(uint8_t)); if (tmpIdentity == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16845, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc err", 0, 0, 0, 0); ret = HITLS_MEMALLOC_FAIL; break; } (void)memcpy_s(tmpIdentity, identityUsedLen + 1, identity, identityUsedLen); uint8_t *tmpPsk = (uint8_t *)BSL_SAL_Dump(psk, pskUsedLen); if (tmpPsk == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16846, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_SAL_FREE(tmpIdentity); ret = HITLS_MEMALLOC_FAIL; break; } BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo->identity); ctx->hsCtx->kxCtx->pskInfo->identity = tmpIdentity; ctx->hsCtx->kxCtx->pskInfo->identityLen = identityUsedLen; BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo->psk); ctx->hsCtx->kxCtx->pskInfo->psk = tmpPsk; ctx->hsCtx->kxCtx->pskInfo->pskLen = pskUsedLen; } while (false); (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); BSL_ERR_PUSH_ERROR(ret); return ret; } #endif /* HITLS_TLS_FEATURE_PSK */
2301_79861745/bench_create
tls/handshake/common/src/hs_kx.c
C
unknown
34,033
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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" #include "securec.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 "hs_kx.h" #include "transcript_hash.h" #include "hs_verify.h" #define HS_VERIFY_DATA_LEN 12u #define CLIENT_FINISHED_LABEL "client finished" #define SERVER_FINISHED_LABEL "server finished" #ifdef HITLS_TLS_PROTO_TLS13 #define MSG_HASH_HEADER_SIZE 4 /* message_hash message header length */ #define MAX_MSG_HASH_SIZE (MAX_DIGEST_SIZE + MSG_HASH_HEADER_SIZE) /* Maximum message_hash message length */ #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_TLS13 #define TLS13_CLIENT_CERT_VERIFY_LABEL "TLS 1.3, client CertificateVerify" #define TLS13_SERVER_CERT_VERIFY_LABEL "TLS 1.3, server CertificateVerify" #define TLS13_CERT_VERIFY_PREFIX 0x20 /* The signature data in TLS 1.3 is firstly filled with 64 0x20s */ #define TLS13_CERT_VERIFY_PREFIX_LEN 64 #endif /* #ifdef HITLS_TLS_PROTO_TLS13 */ int32_t VERIFY_Init(HS_Ctx *hsCtx) { VERIFY_Deinit(hsCtx); VerifyCtx *verifyCtx = (VerifyCtx *)BSL_SAL_Calloc(1u, sizeof(VerifyCtx)); if (verifyCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15475, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify init error: out of memory.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } verifyCtx->dataBuf = (HsMsgCache *)BSL_SAL_Calloc(1u, sizeof(HsMsgCache)); if (verifyCtx->dataBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15476, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify databuf malloc error: out of memory.", 0, 0, 0, 0); BSL_SAL_FREE(verifyCtx); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } hsCtx->verifyCtx = verifyCtx; return HITLS_SUCCESS; } void VERIFY_Deinit(HS_Ctx *hsCtx) { if (hsCtx == NULL) { return; } VerifyCtx *verifyCtx = hsCtx->verifyCtx; if (verifyCtx == NULL) { return; } if (verifyCtx->hashCtx != NULL) { SAL_CRYPT_DigestFree(verifyCtx->hashCtx); } VERIFY_FreeMsgCache(verifyCtx); BSL_SAL_FREE(verifyCtx); hsCtx->verifyCtx = NULL; return; } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION static int32_t SaveVerifyData(TLS_Ctx *ctx, bool isClient) { VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; uint8_t *verifyData = isClient ? ctx->negotiatedInfo.clientVerifyData : ctx->negotiatedInfo.serverVerifyData; if (memcpy_s(verifyData, MAX_DIGEST_SIZE, verifyCtx->verifyData, verifyCtx->verifyDataSize) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15909, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy verifyData fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } if (isClient) { ctx->negotiatedInfo.clientVerifyDataSize = verifyCtx->verifyDataSize; } else { ctx->negotiatedInfo.serverVerifyDataSize = verifyCtx->verifyDataSize; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ int32_t VERIFY_CalcVerifyData(TLS_Ctx *ctx, bool isClient, const uint8_t *masterSecret, uint32_t masterSecretLen) { int32_t ret = HITLS_SUCCESS; uint32_t digestLen = MAX_DIGEST_SIZE; uint8_t digest[MAX_DIGEST_SIZE] = {0}; VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; ret = VERIFY_CalcSessionHash(verifyCtx, digest, &digestLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15477, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify data calculate error: calc session hash fail.", 0, 0, 0, 0); return ret; } CRYPT_KeyDeriveParameters deriveInfo; deriveInfo.hashAlgo = verifyCtx->hashAlgo; deriveInfo.secret = masterSecret; deriveInfo.secretLen = masterSecretLen; deriveInfo.label = isClient ? ((const uint8_t *)CLIENT_FINISHED_LABEL) : ((const uint8_t *)SERVER_FINISHED_LABEL); deriveInfo.labelLen = isClient ? strlen(CLIENT_FINISHED_LABEL) : strlen(SERVER_FINISHED_LABEL); deriveInfo.seed = digest; deriveInfo.seedLen = digestLen; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); ret = SAL_CRYPT_PRF(&deriveInfo, verifyCtx->verifyData, HS_VERIFY_DATA_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15478, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify data calculate error: PRF fail.", 0, 0, 0, 0); return ret; } verifyCtx->verifyDataSize = HS_VERIFY_DATA_LEN; #ifdef HITLS_TLS_FEATURE_RENEGOTIATION ret = SaveVerifyData(ctx, isClient); #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ return ret; } static uint32_t GetHsDataLen(const VerifyCtx *ctx) { uint32_t len = 0; const HsMsgCache *block = ctx->dataBuf; /* Calculate the signature data length */ while (block != NULL) { len += block->dataSize; block = block->next; } return len; } static void LoopBlocks(const HsMsgCache *block, uint8_t *data, uint32_t len) { uint32_t offset = 0; while ((block != NULL) && (block->dataSize > 0)) { (void) memcpy_s(data + offset, len - offset, block->data, block->dataSize); offset += block->dataSize; block = block->next; } } static int32_t GetHsData(VerifyCtx *ctx, uint8_t **data, uint32_t *dataLen) { uint32_t hsDataLen = GetHsDataLen(ctx); if (hsDataLen == 0) { *dataLen = 0; *data = NULL; return HITLS_SUCCESS; } uint8_t *hsData = BSL_SAL_Malloc(hsDataLen); if (hsData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16847, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Malloc fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } const HsMsgCache *block = ctx->dataBuf; LoopBlocks(block, hsData, hsDataLen); *dataLen = hsDataLen; *data = hsData; return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 /* The sender packs the data, calculates the binder, and then appends verified data. * The receiver parses the data, and then calculates the binder. */ static int32_t GetHsDataForBinder(VerifyCtx *ctx, uint32_t *dataLen, bool isClient, uint8_t **data) { if (isClient) { return GetHsData(ctx, data, dataLen); } const HsMsgCache *block = ctx->dataBuf; if (block == NULL || block->next == NULL || block->next->data == 0) { return HITLS_SUCCESS; } uint32_t lenExcludeLastBlock = 0; /* Calculate the total length excluding the last block. */ while (block->next != NULL && block->next->dataSize != 0) { lenExcludeLastBlock += block->dataSize; block = block->next; } uint32_t lastBlockLen = block->dataSize; if (lenExcludeLastBlock == 0) { *data = NULL; *dataLen = lenExcludeLastBlock; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15479, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "In verify ctx, empty data.", 0, 0, 0, 0); return HITLS_SUCCESS; } uint8_t *hsData = BSL_SAL_Malloc(lenExcludeLastBlock + lastBlockLen); if (hsData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16869, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Malloc fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)LoopBlocks(ctx->dataBuf, hsData, lenExcludeLastBlock + lastBlockLen); *dataLen = lenExcludeLastBlock; *data = hsData; return HITLS_SUCCESS; } static const char *GetCertVerifyLabel(bool isClient, uint32_t *len) { if (isClient) { *len = strlen(TLS13_CLIENT_CERT_VERIFY_LABEL); return TLS13_CLIENT_CERT_VERIFY_LABEL; } *len = strlen(TLS13_SERVER_CERT_VERIFY_LABEL); return TLS13_SERVER_CERT_VERIFY_LABEL; } static uint8_t *Tls13GetUnsignData(TLS_Ctx *ctx, uint32_t *dataLen, bool isClient) { VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; uint32_t digestLen = MAX_DIGEST_SIZE; uint8_t digest[MAX_DIGEST_SIZE] = {0}; int32_t ret = VERIFY_CalcSessionHash(verifyCtx, digest, &digestLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15480, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "calc session hash fail when get unsign data.", 0, 0, 0, 0); return NULL; } uint32_t labelLen = 0; const char *label = GetCertVerifyLabel(isClient, &labelLen); /* sixty-four 0x20 s + label + 0x00 + SessionHash */ uint32_t unsignDataLen = TLS13_CERT_VERIFY_PREFIX_LEN + labelLen + 1 + digestLen; uint8_t *unsignData = BSL_SAL_Malloc(unsignDataLen); if (unsignData == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15481, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc unsignData fail when get unsign data.", 0, 0, 0, 0); return NULL; } uint32_t offset = 0; /* Filled prefix: sixty-four 0x20 s */ (void)memset_s(unsignData, unsignDataLen, TLS13_CERT_VERIFY_PREFIX, TLS13_CERT_VERIFY_PREFIX_LEN); offset += TLS13_CERT_VERIFY_PREFIX_LEN; /* Filled labels */ if (memcpy_s(&unsignData[offset], unsignDataLen - offset, label, labelLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16870, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); BSL_SAL_FREE(unsignData); return NULL; } offset += labelLen; /* Filled with one 0 */ unsignData[offset] = 0; offset++; /* Filled SessionHash */ if (memcpy_s(&unsignData[offset], unsignDataLen - offset, digest, digestLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16871, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); BSL_SAL_FREE(unsignData); return NULL; } *dataLen = unsignDataLen; return unsignData; } #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_TLCP11 static uint8_t *TlcpGetUnsignData(TLS_Ctx *ctx, uint32_t *dataLen) { int32_t ret = HITLS_SUCCESS; uint32_t unsignDataLen = MAX_DIGEST_SIZE; uint8_t *unsignData = BSL_SAL_Malloc(unsignDataLen); if (unsignData == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16214, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc unsignData fail when get unsign data", 0, 0, 0, 0); return NULL; } VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; ret = VERIFY_CalcSessionHash(verifyCtx, unsignData, &unsignDataLen); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_SAL_Free(unsignData); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16215, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "calc session hash fail when get unsign data", 0, 0, 0, 0); return NULL; } *dataLen = unsignDataLen; return unsignData; } #endif static uint8_t *GetUnsignData(TLS_Ctx *ctx, uint32_t *dataLen, bool isClient, HITLS_HashAlgo hashAlgo) { (void)isClient; (void)hashAlgo; #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { return Tls13GetUnsignData(ctx, dataLen, isClient); } #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_TLCP11 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { return TlcpGetUnsignData(ctx, dataLen); } #endif uint8_t *data = NULL; (void)GetHsData(ctx->hsCtx->verifyCtx, &data, dataLen); return data; } int32_t VERIFY_CalcSignData(TLS_Ctx *ctx, HITLS_CERT_Key *privateKey, HITLS_SignHashAlgo signScheme) { int32_t ret = HITLS_SUCCESS; HITLS_SignAlgo signAlgo = 0; HITLS_HashAlgo hashAlgo = 0; VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; if (CFG_GetSignParamBySchemes(ctx, signScheme, &signAlgo, &hashAlgo) != true) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15482, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get sign parm fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); return HITLS_PACK_SIGNATURE_ERR; } /* Obtaining the data to be signed */ uint32_t dataLen = 0u; uint8_t *data = GetUnsignData(ctx, &dataLen, ctx->isClient, hashAlgo); // 签名的时候使用的是本端的isClient if (data == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16872, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetUnsignData fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_GET_UNSIGN_DATA_FAIL); return HITLS_MSG_HANDLE_GET_UNSIGN_DATA_FAIL; } CERT_SignParam signParam = {0}; signParam.signAlgo = signAlgo; signParam.hashAlgo = hashAlgo; signParam.data = data; signParam.dataLen = dataLen; signParam.sign = verifyCtx->verifyData; signParam.signLen = MAX_SIGN_SIZE; ret = SAL_CERT_CreateSign(ctx, privateKey, &signParam); if ((ret != HITLS_SUCCESS) || (signParam.signLen > MAX_SIGN_SIZE)) { BSL_SAL_FREE(data); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15483, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "create signature fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); return HITLS_PACK_SIGNATURE_ERR; } verifyCtx->verifyDataSize = signParam.signLen; BSL_SAL_FREE(data); return HITLS_SUCCESS; } int32_t VERIFY_VerifySignData(TLS_Ctx *ctx, HITLS_CERT_Key *pubkey, HITLS_SignHashAlgo signScheme, const uint8_t *signData, uint16_t signDataLen) { int32_t ret = HITLS_SUCCESS; HITLS_SignAlgo signAlgo = 0; HITLS_HashAlgo hashAlgo = 0; if (CFG_GetSignParamBySchemes(ctx, signScheme, &signAlgo, &hashAlgo) != true) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15484, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get sign parm fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); return HITLS_PACK_SIGNATURE_ERR; } /* Obtain the data to be signed */ uint32_t dataLen = 0; uint8_t *data = GetUnsignData(ctx, &dataLen, !ctx->isClient, hashAlgo); if (data == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16873, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get data fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_GET_UNSIGN_DATA_FAIL); return HITLS_MSG_HANDLE_GET_UNSIGN_DATA_FAIL; } CERT_SignParam signParam = {.signAlgo = signAlgo, .hashAlgo = hashAlgo, .data = data, .dataLen = dataLen}; signParam.sign = BSL_SAL_Dump(signData, signDataLen); if (signParam.sign == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16874, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dump fail", 0, 0, 0, 0); BSL_SAL_FREE(data); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } signParam.signLen = signDataLen; ret = SAL_CERT_VerifySign(ctx, pubkey, &signParam); BSL_SAL_FREE(signParam.sign); BSL_SAL_FREE(data); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECRYPT_ERROR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15485, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "verify signature fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_VERIFY_SIGN_FAIL); return HITLS_MSG_HANDLE_VERIFY_SIGN_FAIL; } return HITLS_SUCCESS; } int32_t VERIFY_GetVerifyData(const VerifyCtx *ctx, uint8_t *verifyData, uint32_t *verifyDataLen) { if (ctx->verifyDataSize > MAX_DIGEST_SIZE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15488, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Get verify data error: incorrect digest size.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN); return HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN; } if (memcpy_s(verifyData, *verifyDataLen, ctx->verifyData, ctx->verifyDataSize) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15489, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Get verify data error: memcpy fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } *verifyDataLen = ctx->verifyDataSize; return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 static uint8_t *GetBaseKey(TLS_Ctx *ctx, bool isClient) { uint8_t *baseKey = NULL; #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState == PHA_REQUESTED) { baseKey = isClient ? ctx->clientAppTrafficSecret : ctx->serverAppTrafficSecret; } else #endif /* HITLS_TLS_FEATURE_PHA */ { baseKey = isClient ? ctx->hsCtx->clientHsTrafficSecret : ctx->hsCtx->serverHsTrafficSecret; } return baseKey; } int32_t VERIFY_Tls13CalcVerifyData(TLS_Ctx *ctx, bool isClient) { int32_t ret = HITLS_SUCCESS; HITLS_HashAlgo hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16875, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint8_t finishedKey[MAX_DIGEST_SIZE] = {0}; uint8_t *baseKey = NULL; baseKey = GetBaseKey(ctx, isClient); /* finished_key = HKDF-Expand-Label(BaseKey, "finished", "", Hash.length) */ ret = HS_TLS13DeriveFinishedKey(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlg, baseKey, hashLen, finishedKey, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16876, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveFinishedKey fail", 0, 0, 0, 0); return ret; } VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; uint32_t digestLen = MAX_DIGEST_SIZE; uint8_t digest[MAX_DIGEST_SIZE] = {0}; ret = VERIFY_CalcSessionHash(verifyCtx, digest, &digestLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15490, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "calc session hash fail when calc tls13 verify data.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } /* verify_data = HMAC(finished_key, Transcript-Hash(Handshake Context, Certificate*, CertificateVerify*)) */ verifyCtx->verifyDataSize = hashLen; ret = SAL_CRYPT_Hmac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlg, finishedKey, hashLen, digest, digestLen, verifyCtx->verifyData, &verifyCtx->verifyDataSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15910, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SAL_CRYPT_Hmac fail when calc tls13 verify data.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); } return ret; } static int32_t ConstructMsgHash(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, HsMsgCache *dataBuf, uint8_t *out, uint32_t *outLen) { int32_t ret = HITLS_SUCCESS; uint32_t digestLen = *outLen - MSG_HASH_HEADER_SIZE; uint32_t inLen = dataBuf->dataSize; uint8_t *in = BSL_SAL_Dump(dataBuf->data, dataBuf->dataSize); if (in == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16877, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(BSL_UIO_MEM_ALLOC_FAIL); return BSL_UIO_MEM_ALLOC_FAIL; } ret = SAL_CRYPT_Digest(libCtx, attrName, hashAlgo, in, inLen, &out[MSG_HASH_HEADER_SIZE], &digestLen); BSL_SAL_FREE(in); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16878, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Digest fail", 0, 0, 0, 0); return ret; } uint32_t offset = 0; out[offset++] = MESSAGE_HASH; out[offset++] = 0; out[offset++] = 0; out[offset] = (uint8_t)digestLen; *outLen = digestLen + MSG_HASH_HEADER_SIZE; return HITLS_SUCCESS; } static int32_t ReinitVerify(TLS_Ctx *ctx, uint8_t *msgHash, uint32_t msgHashLen, uint8_t *hrr, uint32_t hrrLen) { int32_t ret = HITLS_SUCCESS; VERIFY_Deinit(ctx->hsCtx); ret = VERIFY_Init(ctx->hsCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16879, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VERIFY_Init fail", 0, 0, 0, 0); return ret; } VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; ret = VERIFY_Append(verifyCtx, msgHash, msgHashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16880, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VERIFY_Append fail", 0, 0, 0, 0); return ret; } return VERIFY_Append(verifyCtx, hrr, hrrLen); } int32_t VERIFY_HelloRetryRequestVerifyProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; uint32_t msgHashLen = MAX_MSG_HASH_SIZE; uint8_t msgHash[MAX_MSG_HASH_SIZE] = {0}; VerifyCtx *verifyCtx = ctx->hsCtx->verifyCtx; HsMsgCache *dataBuf = verifyCtx->dataBuf; /** Set the verify information. */ ret = VERIFY_SetHash(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), ctx->hsCtx->verifyCtx, ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15491, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set verify info fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return ret; } ret = ConstructMsgHash(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), verifyCtx->hashAlgo, dataBuf, msgHash, &msgHashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15493, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "construct msg hash fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return ret; } dataBuf = dataBuf->next; uint32_t helloRetryRequestLen = dataBuf->dataSize; uint8_t *helloRetryRequest = BSL_SAL_Dump(dataBuf->data, dataBuf->dataSize); if (helloRetryRequest == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15494, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc helloRetryRequest fail when process hrr verify.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } ret = ReinitVerify(ctx, msgHash, msgHashLen, helloRetryRequest, helloRetryRequestLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(helloRetryRequest); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return ret; } BSL_SAL_FREE(helloRetryRequest); return HITLS_SUCCESS; } /* Transcript-Hash(Truncate(ClientHello1)) Where Truncate() removes the binders list from the ClientHello If the server responds with a HelloRetryRequest and the client then sends ClientHello2, its binder will be computed over: Transcript-Hash(ClientHello1, HelloRetryRequest, Truncate(ClientHello2)) */ int32_t VERIFY_CalcPskBinder(const TLS_Ctx *ctx, HITLS_HashAlgo hashAlgo, bool isExternalPsk, uint8_t *psk, uint32_t pskLen, const uint8_t *msg, uint32_t msgLen, uint8_t *binder, uint32_t binderLen) { int32_t ret = HITLS_SUCCESS; HITLS_HASH_Ctx *hashCtx = NULL; uint8_t *hsData = NULL; uint8_t earlySecret[MAX_DIGEST_SIZE] = {0}; uint8_t binderKey[MAX_DIGEST_SIZE] = {0}; uint8_t finishedKey[MAX_DIGEST_SIZE] = {0}; uint8_t transcriptHash[MAX_DIGEST_SIZE] = {0}; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlgo); uint32_t hsDataLen = 0u; uint32_t calcBinderLen = binderLen; if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16881, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } // HKDF.Extract PSK to compute EarlySecret ret = HS_TLS13DeriveEarlySecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlgo, psk, pskLen, earlySecret, &hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16882, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveEarlySecret fail", 0, 0, 0, 0); goto EXIT; } // HKDF.Expand EarlySecret to compute BinderKey ret = HS_TLS13DeriveBinderKey(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlgo, isExternalPsk, earlySecret, hashLen, binderKey, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16883, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveBinderKey fail", 0, 0, 0, 0); goto EXIT; } // HKDF.Expand BinderKey to compute Binder Finished Key ret = HS_TLS13DeriveFinishedKey(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlgo, binderKey, hashLen, finishedKey, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16884, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveFinishedKey fail", 0, 0, 0, 0); goto EXIT; } hashCtx = SAL_CRYPT_DigestInit(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlgo); if (hashCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16885, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestInit fail", 0, 0, 0, 0); ret = HITLS_CRYPT_ERR_DIGEST; goto EXIT; } ret = GetHsDataForBinder(ctx->hsCtx->verifyCtx, &hsDataLen, ctx->isClient, &hsData); if (ret != HITLS_SUCCESS) { goto EXIT; } if (hsData != NULL) { ret = SAL_CRYPT_DigestUpdate(hashCtx, hsData, hsDataLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16886, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestUpdate fail", 0, 0, 0, 0); goto EXIT; } } if (SAL_CRYPT_DigestUpdate(hashCtx, msg, msgLen) != HITLS_SUCCESS || SAL_CRYPT_DigestFinal(hashCtx, transcriptHash, &hashLen) != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16887, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestUpdate or DigestFinal fail", 0, 0, 0, 0); ret = HITLS_CRYPT_ERR_DIGEST; goto EXIT; } ret = SAL_CRYPT_Hmac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlgo, finishedKey, hashLen, transcriptHash, hashLen, binder, &calcBinderLen); EXIT: BSL_SAL_CleanseData(earlySecret, MAX_DIGEST_SIZE); BSL_SAL_CleanseData(binderKey, MAX_DIGEST_SIZE); BSL_SAL_CleanseData(finishedKey, MAX_DIGEST_SIZE); BSL_SAL_FREE(hsData); SAL_CRYPT_DigestFree(hashCtx); return ret; } #endif /* HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/common/src/hs_verify.c
C
unknown
27,620
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_TLS13 #include <stdbool.h> #include "securec.h" #include "bsl_bytes.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "hitls_error.h" #include "hitls_crypt_type.h" #include "tls.h" #include "crypt.h" #include "rec.h" #include "hs_kx.h" #include "hs_common.h" #include "transcript_hash.h" #include "config_type.h" int32_t HS_TLS13DeriveSecret(CRYPT_KeyDeriveParameters *deriveInfo, bool isHashed, uint8_t *outSecret, uint32_t outLen) { int32_t ret; uint8_t transcriptHash[MAX_DIGEST_SIZE] = {0}; uint32_t hashLen = SAL_CRYPT_DigestSize(deriveInfo->hashAlgo); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16888, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } if (!isHashed) { ret = SAL_CRYPT_Digest(deriveInfo->libCtx, deriveInfo->attrName, deriveInfo->hashAlgo, deriveInfo->seed, deriveInfo->seedLen, transcriptHash, &hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16889, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Digest fail", 0, 0, 0, 0); return ret; } deriveInfo->seed = transcriptHash; deriveInfo->seedLen = hashLen; } return SAL_CRYPT_HkdfExpandLabel(deriveInfo, outSecret, outLen); } int32_t TLS13HkdfExtract(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CRYPT_HkdfExtractInput *extractInput, uint8_t *prk, uint32_t *prkLen) { uint32_t hashLen = SAL_CRYPT_DigestSize(extractInput->hashAlgo); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16890, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint8_t zeros[MAX_DIGEST_SIZE] = {0}; if (extractInput->salt == NULL) { extractInput->salt = zeros; extractInput->saltLen = hashLen; } if (extractInput->inputKeyMaterial == NULL) { extractInput->inputKeyMaterial = zeros; extractInput->inputKeyMaterialLen = hashLen; } return SAL_CRYPT_HkdfExtract(libCtx, attrName, extractInput, prk, prkLen); } /* 0 | v PSK -> HKDF-Extract = Early Secret */ int32_t HS_TLS13DeriveEarlySecret(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, uint8_t *psk, uint32_t pskLen, uint8_t *earlySecret, uint32_t *outLen) { HITLS_CRYPT_HkdfExtractInput extractInput = {0}; extractInput.hashAlgo = hashAlgo; extractInput.salt = NULL; extractInput.saltLen = 0; extractInput.inputKeyMaterial = psk; extractInput.inputKeyMaterialLen = pskLen; return TLS13HkdfExtract(libCtx, attrName, &extractInput, earlySecret, outLen); } int32_t HS_TLS13DeriveBinderKey(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, bool isExternalPsk, uint8_t *earlySecret, uint32_t secretLen, uint8_t *binderKey, uint32_t keyLen) { uint8_t *binderLabel; uint32_t labelLen; uint8_t extBinderLabel[] = "ext binder"; uint8_t resBinderLabel[] = "res binder"; if (isExternalPsk) { binderLabel = extBinderLabel; labelLen = sizeof(extBinderLabel) - 1; } else { binderLabel = resBinderLabel; labelLen = sizeof(resBinderLabel) - 1; } CRYPT_KeyDeriveParameters deriveInfo = {0}; deriveInfo.hashAlgo = hashAlgo; deriveInfo.secret = earlySecret; deriveInfo.secretLen = secretLen; deriveInfo.label = binderLabel; deriveInfo.labelLen = labelLen; deriveInfo.seed = NULL; deriveInfo.seedLen = 0; deriveInfo.libCtx = libCtx; deriveInfo.attrName = attrName; return HS_TLS13DeriveSecret(&deriveInfo, false, binderKey, keyLen); } /* Early Secret | v Derive-Secret(., "derived", "") | v (EC)DHE -> HKDF-Extract = Handshake Secret | v Derive-Secret(., "derived", "") | v 0 -> HKDF-Extract = Master Secret */ int32_t HS_TLS13DeriveNextStageSecret(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, uint8_t *inSecret, uint32_t inLen, uint8_t *givenSecret, uint32_t givenLen, uint8_t *outSecret, uint32_t *outLen) { int32_t ret; uint8_t label[] = "derived"; uint8_t tmpSecret[MAX_DIGEST_SIZE]; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlgo); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16891, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } CRYPT_KeyDeriveParameters deriveInfo = {0}; deriveInfo.hashAlgo = hashAlgo; deriveInfo.secret = inSecret; deriveInfo.secretLen = inLen; deriveInfo.label = label; deriveInfo.labelLen = sizeof(label) - 1; deriveInfo.seed = NULL; deriveInfo.seedLen = 0; deriveInfo.libCtx = libCtx; deriveInfo.attrName = attrName; ret = HS_TLS13DeriveSecret(&deriveInfo, false, tmpSecret, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16892, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveSecret fail", 0, 0, 0, 0); return ret; } HITLS_CRYPT_HkdfExtractInput extractInput = {0}; extractInput.hashAlgo = hashAlgo; extractInput.salt = tmpSecret; extractInput.saltLen = hashLen; extractInput.inputKeyMaterial = givenSecret; extractInput.inputKeyMaterialLen = givenLen; ret = TLS13HkdfExtract(libCtx, attrName, &extractInput, outSecret, outLen); BSL_SAL_CleanseData(tmpSecret, MAX_DIGEST_SIZE); return ret; } int32_t TLS13DeriveDheSecret(TLS_Ctx *ctx, uint8_t *preMasterSecret, uint32_t *preMasterSecretLen, uint32_t hashLen) { KeyExchCtx *keyCtx = ctx->hsCtx->kxCtx; if (keyCtx->peerPubkey == NULL) { *preMasterSecretLen = hashLen; return HITLS_SUCCESS; } const TLS_GroupInfo *groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, ctx->negotiatedInfo.negotiatedGroup); if (groupInfo == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16244, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "group info not found", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } if (!groupInfo->isKem) { return SAL_CRYPT_CalcEcdhSharedSecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), keyCtx->key, keyCtx->peerPubkey, keyCtx->pubKeyLen, preMasterSecret, preMasterSecretLen); } #ifdef HITLS_TLS_FEATURE_KEM if (ctx->isClient) { return SAL_CRYPT_KemDecapsulate(keyCtx->key, keyCtx->peerPubkey, keyCtx->pubKeyLen, preMasterSecret, preMasterSecretLen); } BSL_SAL_Free(keyCtx->ciphertext); keyCtx->ciphertext = BSL_SAL_Calloc(1, groupInfo->ciphertextLen); if (keyCtx->ciphertext == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16245, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ciphertext malloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } keyCtx->ciphertextLen = groupInfo->ciphertextLen; return SAL_CRYPT_KemEncapsulate(ctx, &(HITLS_KemEncapsulateParams){ .groupId = ctx->negotiatedInfo.negotiatedGroup, .peerPubkey = keyCtx->peerPubkey, .pubKeyLen = keyCtx->pubKeyLen, .ciphertext = keyCtx->ciphertext, .ciphertextLen = &keyCtx->ciphertextLen, .sharedSecret = preMasterSecret, .sharedSecretLen = preMasterSecretLen, }); #else return HITLS_INTERNAL_EXCEPTION; #endif } /* Early Secret | v Derive-Secret(., "derived", "") | v (EC)DHE -> HKDF-Extract = Handshake Secret */ int32_t TLS13DeriveHandshakeSecret(TLS_Ctx *ctx) { uint16_t hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16893, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint8_t preMasterSecret[MAX_PRE_MASTER_SECRET_SIZE] = {0}; uint32_t preMasterSecretLen = MAX_PRE_MASTER_SECRET_SIZE; int32_t ret = TLS13DeriveDheSecret(ctx, preMasterSecret, &preMasterSecretLen, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16894, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveDheSecret fail", 0, 0, 0, 0); return ret; } uint32_t handshakeSecretLen = hashLen; ret = HS_TLS13DeriveNextStageSecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlg, ctx->hsCtx->earlySecret, hashLen, preMasterSecret, preMasterSecretLen, ctx->hsCtx->handshakeSecret, &handshakeSecretLen); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16895, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "DeriveNextStageSecret finish", 0, 0, 0, 0); BSL_SAL_CleanseData(preMasterSecret, MAX_PRE_MASTER_SECRET_SIZE); return ret; } /* (EC)DHE -> HKDF-Extract = Handshake Secret | v Derive-Secret(., "derived", "") | v 0 -> HKDF-Extract = Master Secret */ int32_t TLS13DeriveMasterSecret(TLS_Ctx *ctx) { uint16_t hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16896, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint32_t masterKeyLen = hashLen; return HS_TLS13DeriveNextStageSecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlg, ctx->hsCtx->handshakeSecret, hashLen, NULL, 0, ctx->hsCtx->masterKey, &masterKeyLen); } /* finished_key = HKDF-Expand-Label(BaseKey, "finished", "", Hash.length) */ int32_t HS_TLS13DeriveFinishedKey(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, uint8_t *baseKey, uint32_t baseKeyLen, uint8_t *finishedkey, uint32_t finishedkeyLen) { uint8_t label[] = "finished"; CRYPT_KeyDeriveParameters deriveInfo = {0}; deriveInfo.hashAlgo = hashAlgo; deriveInfo.secret = baseKey; deriveInfo.secretLen = baseKeyLen; deriveInfo.label = label; deriveInfo.labelLen = sizeof(label) - 1; deriveInfo.seed = NULL; deriveInfo.seedLen = 0; deriveInfo.libCtx = libCtx; deriveInfo.attrName = attrName; return SAL_CRYPT_HkdfExpandLabel(&deriveInfo, finishedkey, finishedkeyLen); } /* HKDF-Expand-Label(resumption_master_secret, "resumption", ticket_nonce, Hash.length) */ int32_t HS_TLS13DeriveResumePsk(TLS_Ctx *ctx, const uint8_t *ticketNonce, uint32_t ticketNonceSize, uint8_t *resumePsk, uint32_t resumePskLen) { const uint8_t label[] = "resumption"; HITLS_HashAlgo hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16897, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } CRYPT_KeyDeriveParameters deriveInfo = {0}; deriveInfo.hashAlgo = hashAlg; deriveInfo.secret = ctx->resumptionMasterSecret; deriveInfo.secretLen = hashLen; deriveInfo.label = label; deriveInfo.labelLen = sizeof(label) - 1; deriveInfo.seed = ticketNonce; deriveInfo.seedLen = ticketNonceSize; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); return SAL_CRYPT_HkdfExpandLabel(&deriveInfo, resumePsk, resumePskLen); } int32_t TLS13GetTrafficSecretDeriveInfo(TLS_Ctx *ctx, CRYPT_KeyDeriveParameters *deriveInfo, uint8_t *seed, uint32_t seedLen) { uint32_t tmpSeedLen = seedLen; int32_t ret; ret = VERIFY_CalcSessionHash(ctx->hsCtx->verifyCtx, seed, &tmpSeedLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16898, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcSessionHash fail", 0, 0, 0, 0); return ret; } uint16_t hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16899, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } deriveInfo->hashAlgo = hashAlg; deriveInfo->seed = seed; deriveInfo->seedLen = tmpSeedLen; deriveInfo->secretLen = hashLen; return HITLS_SUCCESS; } /* Derive-Secret(Handshake Secret, label, ClientHello...ServerHello) */ int32_t HS_TLS13DeriveHandshakeTrafficSecret(TLS_Ctx *ctx) { uint8_t seed[MAX_DIGEST_SIZE] = {0}; uint32_t seedLen = MAX_DIGEST_SIZE; CRYPT_KeyDeriveParameters deriveInfo = {0}; int32_t ret; ret = TLS13GetTrafficSecretDeriveInfo(ctx, &deriveInfo, seed, seedLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16900, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetTrafficSecretDeriveInfo fail", 0, 0, 0, 0); return ret; } deriveInfo.secret = ctx->hsCtx->handshakeSecret; uint32_t hashLen = deriveInfo.secretLen; uint8_t clientLabel[] = "c hs traffic"; deriveInfo.label = clientLabel; deriveInfo.labelLen = sizeof(clientLabel) - 1; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); ret = HS_TLS13DeriveSecret(&deriveInfo, true, ctx->hsCtx->clientHsTrafficSecret, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16901, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveSecret fail", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_MAINTAIN_KEYLOG HITLS_LogSecret(ctx, CLIENT_HANDSHAKE_LABEL, ctx->hsCtx->clientHsTrafficSecret, deriveInfo.secretLen); #endif /* HITLS_TLS_MAINTAIN_KEYLOG */ uint8_t serverLabel[] = "s hs traffic"; deriveInfo.label = serverLabel; deriveInfo.labelLen = sizeof(serverLabel) - 1; ret = HS_TLS13DeriveSecret(&deriveInfo, true, ctx->hsCtx->serverHsTrafficSecret, hashLen); #ifdef HITLS_TLS_MAINTAIN_KEYLOG HITLS_LogSecret(ctx, SERVER_HANDSHAKE_LABEL, ctx->hsCtx->serverHsTrafficSecret, deriveInfo.secretLen); #endif /* HITLS_TLS_MAINTAIN_KEYLOG */ return ret; } /* Derive-Secret(Master Secret, label, ClientHello...ServerHello) */ int32_t TLS13DeriveApplicationTrafficSecret(TLS_Ctx *ctx) { uint8_t seed[MAX_DIGEST_SIZE] = {0}; uint32_t seedLen = MAX_DIGEST_SIZE; CRYPT_KeyDeriveParameters deriveInfo = {0}; int32_t ret; ret = TLS13GetTrafficSecretDeriveInfo(ctx, &deriveInfo, seed, seedLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16902, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetTrafficSecretDeriveInfo fail", 0, 0, 0, 0); return ret; } deriveInfo.secret = ctx->hsCtx->masterKey; uint32_t hashLen = deriveInfo.secretLen; uint8_t clientLabel[] = "c ap traffic"; deriveInfo.label = clientLabel; deriveInfo.labelLen = sizeof(clientLabel) - 1; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); ret = HS_TLS13DeriveSecret(&deriveInfo, true, ctx->clientAppTrafficSecret, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16903, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveSecret fail", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_MAINTAIN_KEYLOG HITLS_LogSecret(ctx, CLIENT_APPLICATION_LABEL, ctx->clientAppTrafficSecret, deriveInfo.secretLen); #endif /* HITLS_TLS_MAINTAIN_KEYLOG */ uint8_t serverLabel[] = "s ap traffic"; deriveInfo.label = serverLabel; deriveInfo.labelLen = sizeof(serverLabel) - 1; ret = HS_TLS13DeriveSecret(&deriveInfo, true, ctx->serverAppTrafficSecret, hashLen); #ifdef HITLS_TLS_MAINTAIN_KEYLOG HITLS_LogSecret(ctx, SERVER_APPLICATION_LABEL, ctx->serverAppTrafficSecret, deriveInfo.secretLen); #endif /* HITLS_TLS_MAINTAIN_KEYLOG */ return ret; } /* Derive-Secret(., "res master", ClientHello...client Finished) = resumption_master_secret */ #ifdef HITLS_TLS_FEATURE_SESSION int32_t HS_TLS13DeriveResumptionMasterSecret(TLS_Ctx *ctx) { uint8_t seed[MAX_DIGEST_SIZE] = {0}; uint32_t seedLen = MAX_DIGEST_SIZE; CRYPT_KeyDeriveParameters deriveInfo = {0}; int32_t ret; ret = TLS13GetTrafficSecretDeriveInfo(ctx, &deriveInfo, seed, seedLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16904, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetTrafficSecretDeriveInfo fail", 0, 0, 0, 0); return ret; } deriveInfo.secret = ctx->hsCtx->masterKey; uint32_t hashLen = deriveInfo.secretLen; const uint8_t resLabel[] = "res master"; deriveInfo.label = resLabel; deriveInfo.labelLen = sizeof(resLabel) - 1; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); return HS_TLS13DeriveSecret(&deriveInfo, true, ctx->resumptionMasterSecret, hashLen); } #endif /* HITLS_TLS_FEATURE_SESSION */ int32_t HS_TLS13CalcServerHelloProcessSecret(TLS_Ctx *ctx) { PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; uint16_t hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlg); if (hashLen == 0 || hashLen > MAX_DIGEST_SIZE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16906, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint8_t zero[MAX_DIGEST_SIZE] = {0}; uint8_t *psk = NULL; uint32_t pskLen = 0; if (pskInfo->psk != NULL) { psk = pskInfo->psk; pskLen = pskInfo->pskLen; } else { psk = zero; pskLen = hashLen; } uint32_t earlySecretLen = hashLen; int32_t ret = HS_TLS13DeriveEarlySecret(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlg, psk, pskLen, ctx->hsCtx->earlySecret, &earlySecretLen); BSL_SAL_CleanseData(psk, pskLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16907, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveEarlySecret fail", 0, 0, 0, 0); return ret; } return TLS13DeriveHandshakeSecret(ctx); } int32_t HS_TLS13CalcServerFinishProcessSecret(TLS_Ctx *ctx) { int32_t ret; ret = TLS13DeriveMasterSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16908, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveMasterSecret fail", 0, 0, 0, 0); return ret; } ret = TLS13DeriveApplicationTrafficSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16909, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveApplicationTrafficSecret fail", 0, 0, 0, 0); } return ret; } int32_t HS_SwitchTrafficKey(TLS_Ctx *ctx, uint8_t *secret, uint32_t secretLen, bool isOut) { int32_t ret; CipherSuiteInfo *cipherSuiteInfo = &(ctx->negotiatedInfo.cipherSuiteInfo); uint32_t hashLen = SAL_CRYPT_DigestSize(cipherSuiteInfo->hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16910, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } REC_SecParameters keyPara = {0}; ret = HS_SetInitPendingStateParam(ctx, ctx->isClient, &keyPara); if (ret != HITLS_SUCCESS) { return ret; } if (hashLen > sizeof(keyPara.masterSecret)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16911, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "hashLen err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } if (memcpy_s(keyPara.masterSecret, sizeof(keyPara.masterSecret), secret, secretLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16912, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } ret = REC_TLS13InitPendingState(ctx, &keyPara, isOut); (void)memset_s(keyPara.masterSecret, sizeof(keyPara.masterSecret), 0, sizeof(keyPara.masterSecret)); if (ret != HITLS_SUCCESS) { return ret; } /** enable key specification */ return REC_ActivePendingState(ctx, isOut); } /* application_traffic_secret_N+1 = HKDF-Expand-Label(application_traffic_secret_N, "traffic upd", "", Hash.length) */ #ifdef HITLS_TLS_FEATURE_KEY_UPDATE int32_t HS_TLS13UpdateTrafficSecret(TLS_Ctx *ctx, bool isOut) { HITLS_HashAlgo hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; uint32_t hashLen = SAL_CRYPT_DigestSize(hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16913, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint8_t trafficSecret[MAX_DIGEST_SIZE] = {0}; uint8_t *trafficSecretPointer = trafficSecret; uint32_t trafficSecretLen = hashLen; uint8_t *baseKey = NULL; uint32_t baseKeyLen = hashLen; if ((ctx->isClient && isOut) || (!ctx->isClient && !isOut)) { baseKey = ctx->clientAppTrafficSecret; } else { baseKey = ctx->serverAppTrafficSecret; } uint8_t label[] = "traffic upd"; CRYPT_KeyDeriveParameters deriveInfo = {0}; deriveInfo.hashAlgo = hashAlg; deriveInfo.secret = baseKey; deriveInfo.secretLen = baseKeyLen; deriveInfo.label = label; deriveInfo.labelLen = sizeof(label) - 1; deriveInfo.seed = NULL; deriveInfo.seedLen = 0; deriveInfo.libCtx = LIBCTX_FROM_CTX(ctx); deriveInfo.attrName = ATTRIBUTE_FROM_CTX(ctx); int32_t ret = SAL_CRYPT_HkdfExpandLabel(&deriveInfo, trafficSecretPointer, trafficSecretLen); if (ret != HITLS_SUCCESS) { BSL_SAL_CleanseData(trafficSecret, MAX_DIGEST_SIZE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16914, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HkdfExpandLabel fail", 0, 0, 0, 0); return ret; } ret = memcpy_s(baseKey, baseKeyLen, trafficSecret, trafficSecretLen); BSL_SAL_CleanseData(trafficSecret, MAX_DIGEST_SIZE); if (ret != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16915, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } return HS_SwitchTrafficKey(ctx, baseKey, baseKeyLen, isOut); } #endif /* HITLS_TLS_FEATURE_KEY_UPDATE */ #endif /* HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/common/src/tls13key.c
C
unknown
23,307
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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" #include "securec.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 "transcript_hash.h" int32_t VERIFY_SetHash(HITLS_Lib_Ctx *libCtx, const char *attrName, VerifyCtx *ctx, HITLS_HashAlgo hashAlgo) { int32_t ret; /* the value must be the same as the PRF function, use the digest algorithm with SHA-256 or higher strength */ HITLS_HashAlgo prfAlgo = (hashAlgo == HITLS_HASH_SHA1) ? HITLS_HASH_SHA_256 : hashAlgo; ctx->hashCtx = SAL_CRYPT_DigestInit(libCtx, attrName, prfAlgo); if (ctx->hashCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_DIGEST); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15716, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify set hash error: digest init fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } HsMsgCache *dataBuf = ctx->dataBuf; while ((dataBuf != NULL) && (dataBuf->dataSize > 0u)) { ret = SAL_CRYPT_DigestUpdate(ctx->hashCtx, dataBuf->data, dataBuf->dataSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15717, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify set hash error: digest update fail.", 0, 0, 0, 0); SAL_CRYPT_DigestFree(ctx->hashCtx); ctx->hashCtx = NULL; return ret; } dataBuf = dataBuf->next; } ctx->hashAlgo = prfAlgo; return HITLS_SUCCESS; } static HsMsgCache *GetLastCache(HsMsgCache *dataBuf) { HsMsgCache *cacheBuf = dataBuf; while (cacheBuf->next != NULL) { cacheBuf = cacheBuf->next; } return cacheBuf; } static int32_t CacheMsgData(HsMsgCache *dataBuf, const uint8_t *data, uint32_t len) { HsMsgCache *lastCache = GetLastCache(dataBuf); lastCache->next = BSL_SAL_Calloc(1u, sizeof(HsMsgCache)); if (lastCache->next == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15718, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc HsMsgCache fail when append msg.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } BSL_SAL_FREE(lastCache->data); lastCache->data = BSL_SAL_Dump(data, len); if (lastCache->data == NULL) { BSL_SAL_FREE(lastCache->next); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15719, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc HsMsgCache data fail when append msg.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } lastCache->dataSize = len; return HITLS_SUCCESS; } int32_t VERIFY_Append(VerifyCtx *ctx, const uint8_t *data, uint32_t len) { int32_t ret; if (ctx->hashCtx != NULL) { ret = SAL_CRYPT_DigestUpdate(ctx->hashCtx, data, len); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15720, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify append error: digest update fail.", 0, 0, 0, 0); return ret; } } if (ctx->dataBuf != NULL) { return CacheMsgData(ctx->dataBuf, data, len); } return HITLS_SUCCESS; } int32_t VERIFY_CalcSessionHash(VerifyCtx *ctx, uint8_t *digest, uint32_t *digestLen) { int32_t ret; HITLS_HASH_Ctx *tmpHashCtx = SAL_CRYPT_DigestCopy(ctx->hashCtx); if (tmpHashCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_DIGEST); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15721, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify data calculate error: digest copy fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } /* get the hash result */ ret = SAL_CRYPT_DigestFinal(tmpHashCtx, digest, digestLen); SAL_CRYPT_DigestFree(tmpHashCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15722, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Verify data calculate error: digest final fail.", 0, 0, 0, 0); } return ret; } void VERIFY_FreeMsgCache(VerifyCtx *ctx) { HsMsgCache *nextBuf = NULL; HsMsgCache *dataBuf = ctx->dataBuf; while (dataBuf != NULL) { nextBuf = dataBuf->next; BSL_SAL_FREE(dataBuf->data); BSL_SAL_FREE(dataBuf); dataBuf = nextBuf; } ctx->dataBuf = NULL; return; }
2301_79861745/bench_create
tls/handshake/common/src/transcript_hash.c
C
unknown
4,932
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_COOKIE_H #define HS_COOKIE_H #include <stdint.h> #include <stdbool.h> #include "tls.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Calculate the cookie * The mackey is updated each time the number of times that Cookie_SECRET_LIFETIME is calculated. * * @param ctx [IN] Handshake context * @param clientHello [IN] Parsed clientHello structure * @param cookie [OUT] Calculated cookie * @param cookieLen [OUT] Calculated cookie length. * * @retval HITLS_SUCCESS succeeded. * @retval For other error codes, see hitls_error.h. */ int32_t HS_CalcCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint8_t *cookie, uint32_t *cookieLen); /** * @brief Verify the cookie. * If the first cookie verification fails, the previous mackey is used for verification again. * * @param ctx [IN] Handshake context * @param clientHello [IN] Parsed clientHello structure * @param isCookieValid [OUT] Indicates whether the verification is successful. * * @retval HITLS_SUCCESS succeeded. * @retval For other error codes, see hitls_error.h. */ int32_t HS_CheckCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isCookieValid); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_COOKIE_H */
2301_79861745/bench_create
tls/handshake/cookie/include/hs_cookie.h
C
unknown
1,807
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "securec.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 "bsl_bytes.h" #include "bsl_errno.h" #include "sal_net.h" #include "uio_base.h" #include "hitls.h" #include "hitls_error.h" #include "hitls_cookie.h" #include "hitls_crypt_type.h" #include "tls.h" #include "tls_config.h" #include "hs_ctx.h" #include "hs.h" #define MAX_IP_ADDR_SIZE 256u static int32_t UpdateMacKey(TLS_Ctx *ctx, CookieInfo *cookieInfo) { (void)memcpy_s(cookieInfo->preMacKey, MAC_KEY_LEN, cookieInfo->macKey, MAC_KEY_LEN); /* Save the old key */ int32_t ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), cookieInfo->macKey, MAC_KEY_LEN); /* Create a new key */ if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15691, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "generate macKey fail when calc cookie.", 0, 0, 0, 0); return ret; } cookieInfo->algRemainTime = COOKIE_SECRET_LIFETIME; /* Updated the current HMAC algorithm usage times */ return HITLS_SUCCESS; } static void FillCipherSuite(const ClientHelloMsg *clientHello, uint8_t *material, uint32_t *offset) { for (uint32_t i = 0; i < clientHello->cipherSuitesSize; i++) { BSL_Uint16ToByte(clientHello->cipherSuites[i], &material[*offset]); *offset += sizeof(uint16_t); } } /** * @brief Generate cookie calculation materials * @attention The maximum memory required is already applied, so the function does not * need to check whether the memory is out of bounds * * @param ctx [IN] Hitls context * @param clientHello [IN] ClientHello message * @param material [OUT] Returned material * @param materialSize [IN] Maximum length of the material * @param usedLen [OUT] Returned actual material length * * @retval HITLS_SUCCESS * @retval HITLS_MEMCPY_FAIL */ static int32_t GenerateCookieCalcMaterial(const TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint8_t *material, uint32_t materialSize, uint32_t *usedLen) { uint8_t ipAddr[MAX_IP_ADDR_SIZE] = {0}; BSL_UIO_CtrlGetPeerIpAddrParam param = {ipAddr, sizeof(ipAddr)}; uint32_t offset = 0; BSL_SAL_SockAddr peerAddr = NULL; int32_t ret = SAL_SockAddrNew(&peerAddr); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16916, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "addr New fail", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } int32_t peerAddrLen = SAL_SockAddrSize(peerAddr); /* Add the peer IP address */ ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_GET_PEER_IP_ADDR, peerAddrLen, peerAddr); if (ret == BSL_SUCCESS) { if (memcpy_s(ipAddr, MAX_IP_ADDR_SIZE, peerAddr, SAL_SockAddrSize(peerAddr)) != EOK) { SAL_SockAddrFree(peerAddr); return BSL_MEMCPY_FAIL; } param.size = SAL_SockAddrSize(peerAddr); if (memcpy_s(material, materialSize, ipAddr, param.size) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15692, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy ipAddr fail when calc cookie.", 0, 0, 0, 0); SAL_SockAddrFree(peerAddr); return HITLS_MEMCPY_FAIL; } offset += param.size; } SAL_SockAddrFree(peerAddr); /* fill the version */ BSL_Uint16ToByte(clientHello->version, &material[offset]); offset += sizeof(uint16_t); /* fill client's random value */ if (memcpy_s(&material[offset], materialSize - offset, clientHello->randomValue, HS_RANDOM_SIZE) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15693, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy random fail when calc cookie.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } offset += HS_RANDOM_SIZE; /* fill session_id */ if (clientHello->sessionIdSize != 0 && clientHello->sessionId != NULL) { if (memcpy_s(&material[offset], materialSize - offset, clientHello->sessionId, clientHello->sessionIdSize) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15694, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy sessionId fail when calc cookie.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } offset += clientHello->sessionIdSize; } /* fill the cipher suite */ FillCipherSuite(clientHello, material, &offset); *usedLen = offset; return HITLS_SUCCESS; } /** * @brief Add cookie calculation materials to the HMAC. * * @param ctx [IN] Hitls context * @param clientHello [IN] ClientHello message * @param cookieInfo [IN] cookie info * @param cookie [IN] cookie * @param cookieLen [IN] cookie len * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h. */ static int32_t AddCookieCalcMaterial( const TLS_Ctx *ctx, const ClientHelloMsg *clientHello, CookieInfo *cookieInfo, uint8_t *cookie, uint32_t *cookieLen) { /* Add the cookie calculation material, that is, the peer IP address + version + random + sessionID + cipherSuites */ uint32_t materialSize = MAX_IP_ADDR_SIZE + sizeof(uint16_t) + HS_RANDOM_SIZE + clientHello->sessionIdSize + clientHello->cipherSuitesSize * sizeof(uint16_t); uint8_t *material = BSL_SAL_Calloc(1u, materialSize); if (material == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15695, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "material malloc fail when calc cookie.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } int32_t ret; uint32_t usedLen = 0; ret = GenerateCookieCalcMaterial(ctx, clientHello, material, materialSize, &usedLen); if (ret != HITLS_SUCCESS) { (void)memset_s(material, materialSize, 0, materialSize); BSL_SAL_FREE(material); return ret; } ret = SAL_CRYPT_Hmac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), HITLS_HASH_SHA_256, cookieInfo->macKey, MAC_KEY_LEN, material, usedLen, cookie, cookieLen); (void)memset_s(material, materialSize, 0, materialSize); BSL_SAL_FREE(material); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15696, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SAL_CRYPT_Hmac fail when calc cookie.", 0, 0, 0, 0); } return ret; } int32_t HS_CalcCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint8_t *cookie, uint32_t *cookieLen) { /* If the user's cookie calculation callback is registered, use the user's callback interface */ if (ctx->globalConfig != NULL && ctx->globalConfig->appGenCookieCb != NULL) { int32_t returnVal = ctx->globalConfig->appGenCookieCb(ctx, cookie, cookieLen); /* A return value of zero indicates that the cookie generation failed, and a return value of other values is a * success, so the judgment here is a failure rather than a non-success */ if (returnVal == HITLS_COOKIE_GENERATE_ERROR) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_COOKIE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15697, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "appGenCookieCb return error 0x%x.", returnVal, 0, 0, 0); return HITLS_MSG_HANDLE_COOKIE_ERR; } if (*cookieLen > TLS_HS_MAX_COOKIE_SIZE) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_COOKIE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17353, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cookie len is too long.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_COOKIE_ERR; } return HITLS_SUCCESS; } /* If the cookie calculation callback is not registered, the default calculation is used */ int32_t ret = HITLS_SUCCESS; CookieInfo *cookieInfo = &ctx->negotiatedInfo.cookieInfo; /* If the number of remaining usage times of the current algorithm is 0, update the algorithm */ if (cookieInfo->algRemainTime == 0) { ret = UpdateMacKey(ctx, cookieInfo); if (ret != HITLS_SUCCESS) { return ret; } } /* Add cookie calculation materials */ ret = AddCookieCalcMaterial(ctx, clientHello, cookieInfo, cookie, cookieLen); if (ret != HITLS_SUCCESS) { return ret; } /* Updated the current HMAC algorithm usage times */ cookieInfo->algRemainTime--; return HITLS_SUCCESS; } static int32_t CheckCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isCookieValid) { uint8_t cookie[TLS_HS_MAX_COOKIE_SIZE] = {0}; uint32_t cookieLen = sizeof(cookie); *isCookieValid = false; /* Calculating cookies will reduce the number of times the algorithm is used. In order to prevent algorithm * switching after calculation, it is increased by itself and then calculated */ ctx->negotiatedInfo.cookieInfo.algRemainTime++; int32_t ret = HS_CalcCookie(ctx, clientHello, cookie, &cookieLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16917, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcCookie fail", 0, 0, 0, 0); return ret; } if ((cookieLen == clientHello->cookieLen) && (memcmp((char *)cookie, (char *)clientHello->cookie, cookieLen) == 0)) { *isCookieValid = true; } (void)memset_s(cookie, TLS_HS_MAX_COOKIE_SIZE, 0, TLS_HS_MAX_COOKIE_SIZE); return HITLS_SUCCESS; } static int32_t CheckCookieWithPreMacKey(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isCookieValid) { uint8_t macKeyStore[MAC_KEY_LEN] = {0}; CookieInfo *cookieInfo = &ctx->negotiatedInfo.cookieInfo; /* If the previous key does not exist, the system will not verify */ if (memcmp(cookieInfo->preMacKey, macKeyStore, MAC_KEY_LEN) == 0) { return HITLS_SUCCESS; } /* Save the current mackey */ (void)memcpy_s(macKeyStore, MAC_KEY_LEN, cookieInfo->macKey, MAC_KEY_LEN); /* Use the previous mackey */ (void)memcpy_s(cookieInfo->macKey, MAC_KEY_LEN, cookieInfo->preMacKey, MAC_KEY_LEN); int32_t ret = CheckCookie(ctx, clientHello, isCookieValid); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16918, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckCookie fail", 0, 0, 0, 0); (void)memset_s(macKeyStore, MAC_KEY_LEN, 0, MAC_KEY_LEN); return ret; } /* Restore the current mackey */ (void)memcpy_s(cookieInfo->macKey, MAC_KEY_LEN, macKeyStore, MAC_KEY_LEN); (void)memset_s(macKeyStore, MAC_KEY_LEN, 0, MAC_KEY_LEN); return HITLS_SUCCESS; } static int32_t CheckCookieDuringRenegotiation(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isCookieValid) { uint8_t *cookie = ctx->negotiatedInfo.cookie; uint16_t cookieLen = (uint16_t)ctx->negotiatedInfo.cookieSize; if ((cookieLen == clientHello->cookieLen) && (memcmp((char *)cookie, (char *)clientHello->cookie, cookieLen) == 0)) { *isCookieValid = true; } return HITLS_SUCCESS; } int32_t HS_CheckCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isCookieValid) { /* The DTLS protocol determines whether cookie verification is required based on user setting */ if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && !ctx->config.tlsConfig.isSupportDtlsCookieExchange && !ctx->isDtlsListen) { *isCookieValid = true; return HITLS_SUCCESS; } *isCookieValid = false; /* If the client does not send the cookie, the verification is not required */ if (clientHello->cookie == NULL) { return HITLS_SUCCESS; } /* In the renegotiation scenario, the cookie stored in the negotiatedInfo is used for verification */ if (ctx->negotiatedInfo.isRenegotiation) { return CheckCookieDuringRenegotiation(ctx, clientHello, isCookieValid); } /* If the user's cookie validation callback is registered, use the user's callback interface */ HITLS_AppVerifyCookieCb cookieCb = ctx->globalConfig->appVerifyCookieCb; if (cookieCb != NULL) { int32_t isValid = cookieCb(ctx, clientHello->cookie, clientHello->cookieLen); /* If the return value is not zero, the cookie is valid, so the judgment here does not equal failure rather than * success */ if (isValid != HITLS_COOKIE_VERIFY_ERROR) { *isCookieValid = true; } return HITLS_SUCCESS; } /* If the cookie validation callback function of the user is not registered, use the default validation function */ int32_t ret = CheckCookie(ctx, clientHello, isCookieValid); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16919, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckCookie fail", 0, 0, 0, 0); return ret; } /* If the cookie is successfully verified for the first time, it is returned. Otherwise, the previous MacKey is used * to verify the cookie again */ if (*isCookieValid) { return HITLS_SUCCESS; } return CheckCookieWithPreMacKey(ctx, clientHello, isCookieValid); } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
2301_79861745/bench_create
tls/handshake/cookie/src/hs_cookie.c
C
unknown
13,909
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_H #define HS_H #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize the handshake context * * @param ctx [IN] TLS object * * @retval HITLS_SUCCESS succeeded */ int32_t HS_Init(TLS_Ctx *ctx); /** * @brief Release the handshake context * * @param ctx [IN] TLS object */ void HS_DeInit(TLS_Ctx *ctx); /** * @brief Establish a TLS connection * * @param ctx [IN] TLS object * * @retval HITLS_SUCCESS The connection is successfully established. * @retval For details about other error codes, see hitls_error.h */ int32_t HS_DoHandshake(TLS_Ctx *ctx); /** * @brief Generate the session key * * @param ctx [IN] TLS context * @param isClient [IN] Client or Not * * @retval HITLS_SUCCESS succeeded * @retval For details about other error codes, see hitls_error.h */ int32_t HS_KeyEstablish(TLS_Ctx *ctx, bool isClient); /** * @brief Session recovery Generate a session key. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS succeeded * @retval For details about other error codes, see hitls_error.h */ int32_t HS_ResumeKeyEstablish(TLS_Ctx *ctx); /** * @brief Obtain the current handshake status * * @param ctx [IN] TLS context * * @retval Current handshake status */ uint32_t HS_GetState(const TLS_Ctx *ctx); /** * @brief Obtain the version number. If the version number is not negotiated, the latest version * supported by the local is returned. * * @param ctx [IN] TLS context * * @return Return the version number. */ uint32_t HS_GetVersion(const TLS_Ctx *ctx); /** * @brief Obtain the handshake status character string. * * @param state [IN] Handshake status * * @return Character string corresponding to the handshake status */ const char *HS_GetStateStr(uint32_t state); /** * @brief Check whether the conditions for sending keyupdate are met * * @param ctx [IN] TLS context * @param updateType [IN] keyupdate type * * @retval HITLS_SUCCESS succeeded. * @retval For details about other error codes, see hitls_error.h */ int32_t HS_CheckKeyUpdateState(TLS_Ctx *ctx, uint32_t updateType); /** * @brief Obtain the server_name in the handshake TLS context. * * @param ctx [IN] TLS context * * @return string of server_name in the TLS context during the handshake */ const char *HS_GetServerName(const TLS_Ctx *ctx); /** * @brief Determine and handle the 2MSL timeout * * @param ctx [IN] TLS context * * @return string of server_name in the TLS context during the handshake */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t HS_CheckAndProcess2MslTimeout(TLS_Ctx *ctx); /** * @brief Send dtls fragment handshake message according to maxRecPayloadLen * * @param ctx [IN] TLS context * @param maxRecPayloadLen [IN] the max plaintext size * @param msgData [IN] the handshake message data need to be send * * @retval HITLS_SUCCESS succeeded. * @retval For details about other error codes, see hitls_error.h */ int32_t HS_DtlsSendFragmentHsMsg(TLS_Ctx *ctx, uint32_t maxRecPayloadLen, const uint8_t *msgData); #endif /** * @brief Get whether the hadshake state is a send state * * @param state [IN] handshake state * * @retval true or false */ bool IsHsSendState(HITLS_HandshakeState state); int32_t HS_CheckPostHandshakeAuth(TLS_Ctx *ctx); #define TLS_IS_FIRST_HANDSHAKE(ctx) ((ctx)->negotiatedInfo.clientVerifyDataSize == 0 \ || (ctx)->negotiatedInfo.serverVerifyDataSize == 0) #ifdef __cplusplus } #endif #endif /* HS_H */
2301_79861745/bench_create
tls/handshake/include/hs.h
C
unknown
4,081
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef PACK_H #define PACK_H #include "tls.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Pack handshake messages * * @param ctx [IN] TLS context * @param type [IN] Message type * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t HS_PackMsg(TLS_Ctx *ctx, HS_MsgType type); /** * @brief Pack uint8_t to buffer * * @param pkt [IN/OUT] Context for packing * @param value [IN] packed data * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackAppendUint8ToBuf(PackPacket *pkt, uint8_t value); /** * @brief Pack uint16_t to buffer * * @param pkt [IN/OUT] Context for packing * @param value [IN] packed data * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackAppendUint16ToBuf(PackPacket *pkt, uint16_t value); /** * @brief Pack uint24_t to buffer * * @param pkt [IN/OUT] Context for packing * @param value [IN] packed data * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackAppendUint24ToBuf(PackPacket *pkt, uint32_t value); /** * @brief Pack uint32_t to buffer * * @param pkt [IN/OUT] Context for packing * @param value [IN] packed data * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackAppendUint32ToBuf(PackPacket *pkt, uint32_t value); /** * @brief Pack uint64_t to buffer * * @param pkt [IN/OUT] Context for packing * @param value [IN] packed data * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackAppendUint64ToBuf(PackPacket *pkt, uint64_t value); /** * @brief Pack data to buffer * * @param pkt [IN/OUT] Context for packing * @param data [IN] packed data * @param size [IN] size of packed data * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackAppendDataToBuf(PackPacket *pkt, const uint8_t *data, uint32_t size); /** * @brief Reserve bytes in the handshake buffer for packing, without increasing offset. * The reservedBuf should be used immediately after this function is called. Since the buffer may be reallocated. * If input reservedBuf == NULL, just prepare Handshake message buffer for handshake message packing. * * @param pkt [IN/OUT] Context for packing * @param size [IN] reserved data size * @param reservedBuf [OUT] reserved buffer pointer * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackReserveBytes(PackPacket *pkt, uint32_t size, uint8_t **reservedBuf); /**  * @brief   It means a buffer with size bytes length is needed to be packed. It reserves bytes to be filled as length. * After the bytes is reserved, the offset will increase, and return the position of the length value. * After the following buffer has been packed, use the PackCloseUintXField fucntion with returned position before to * calculate the length and fill the length value. * * @param pkt [IN/OUT] Context for packing * @param size [IN] allocate data size * @param allocatedPosition [OUT] allocated buffer offset * * @retval HITLS_SUCCESS success * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackStartLengthField(PackPacket *pkt, uint32_t size, uint32_t *allocatedPosition); /** * @brief Increasing offset in the handshake buffer, without allocating memory. * * @param pkt [IN/OUT] Context for packing * @param size [IN] Offset size to skip * * @retval HITLS_SUCCESS success * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackSkipBytes(PackPacket *pkt, uint32_t size); /** * @brief After finish packing a buffer with a uint8_t length, pack the length field at the start of the buffer. * * @param pkt [IN/OUT] Context for packing * @param position [IN] The start position of the field */ void PackCloseUint8Field(PackPacket *pkt, uint32_t position); /** * @brief After finish packing a buffer with a uint16_t length, pack the length field at the start of the buffer. * * @param pkt [IN/OUT] Context for packing * @param position [IN] The start position of the field */ void PackCloseUint16Field(PackPacket *pkt, uint32_t position); /** * @brief After finish packing a buffer with a uint24_t length, pack the length field at the start of the buffer. * * @param pkt [IN/OUT] Context for packing * @param position [IN] The start position of the field */ void PackCloseUint24Field(PackPacket *pkt, uint32_t position); /**  * @brief   Get a subbuffer from the handshake buffer, which starts from the start position, * ends at the current offset, and length is the length of the sub-buffer. * * @attention The reservedBuf should be used immediately after this function is called. * @param pkt [IN] Context for packing * @param start [IN] The start position of the sub-buffer * @param length [OUT] The length of the sub-buffer * @param buf [OUT] The pointer of the sub-buffer * * @retval HITLS_SUCCESS success * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Start exceeds the current offset */ int32_t PackGetSubBuffer(PackPacket *pkt, uint32_t start, uint32_t *length, uint8_t **buf); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif
2301_79861745/bench_create
tls/handshake/pack/include/pack.h
C
unknown
6,479
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdlib.h> #include <stdint.h> #include "hitls_build.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 "tls.h" #include "hs_msg.h" #include "hs_ctx.h" #include "hs.h" #include "pack_msg.h" #include "pack_common.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t PackHsMsgBody(TLS_Ctx *ctx, HS_MsgType type, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; switch (type) { #ifdef HITLS_TLS_HOST_SERVER case SERVER_HELLO: ret = PackServerHello(ctx, pkt); break; #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) case HELLO_VERIFY_REQUEST: ret = PackHelloVerifyRequest(ctx, pkt); break; #endif case SERVER_KEY_EXCHANGE: ret = PackServerKeyExchange(ctx, pkt); break; case CERTIFICATE_REQUEST: ret = PackCertificateRequest(ctx, pkt); break; case HELLO_REQUEST: case SERVER_HELLO_DONE: return HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_SESSION_TICKET case NEW_SESSION_TICKET: ret = PackNewSessionTicket(ctx, pkt); break; #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_HOST_CLIENT case CLIENT_HELLO: ret = PackClientHello(ctx, pkt); break; case CLIENT_KEY_EXCHANGE: ret = PackClientKeyExchange(ctx, pkt); break; case CERTIFICATE_VERIFY: ret = PackCertificateVerify(ctx, pkt); break; #endif /* HITLS_TLS_HOST_CLIENT */ case CERTIFICATE: ret = PackCertificate(ctx, pkt); break; case FINISHED: ret = PackFinished(ctx, pkt); break; default: ret = HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG; break; } if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15812, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack handshake[%u] msg error.", type, 0, 0, 0); } return ret; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t PackTls13HsMsgBody(TLS_Ctx *ctx, HS_MsgType type, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; switch (type) { #ifdef HITLS_TLS_HOST_CLIENT case CLIENT_HELLO: ret = PackClientHello(ctx, pkt); break; #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER case SERVER_HELLO: ret = PackServerHello(ctx, pkt); break; case ENCRYPTED_EXTENSIONS: ret = PackEncryptedExtensions(ctx, pkt); break; case CERTIFICATE_REQUEST: ret = Tls13PackCertificateRequest(ctx, pkt); break; case NEW_SESSION_TICKET: ret = Tls13PackNewSessionTicket(ctx, pkt); break; #endif /* HITLS_TLS_HOST_SERVER */ case CERTIFICATE: ret = Tls13PackCertificate(ctx, pkt); break; case CERTIFICATE_VERIFY: ret = PackCertificateVerify(ctx, pkt); break; case FINISHED: ret = PackFinished(ctx, pkt); break; #ifdef HITLS_TLS_FEATURE_KEY_UPDATE case KEY_UPDATE: ret = PackKeyUpdate(ctx, pkt); break; #endif default: ret = HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG; break; } if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15813, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack handshake[%u] msg error.", type, 0, 0, 0); } return ret; } #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t Dtls12PackMsg(TLS_Ctx *ctx, HS_MsgType type) { uint16_t sequence = 0; int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; PackPacket pkt = {.buf = &hsCtx->msgBuf, .bufLen = &hsCtx->bufferLen, .bufOffset = &hsCtx->msgLen}; uint32_t headerPosition = 0; ret = PackStartLengthField(&pkt, DTLS_HS_MSG_HEADER_SIZE, &headerPosition); if (ret != HITLS_SUCCESS) { return ret; } ret = PackHsMsgBody(ctx, type, &pkt); if (ret != HITLS_SUCCESS) { return ret; } sequence = hsCtx->nextSendSeq; uint8_t *dtlsHeaderBuf = NULL; uint32_t totalLen = 0; ret = PackGetSubBuffer(&pkt, headerPosition, &totalLen, &dtlsHeaderBuf); if (ret != HITLS_SUCCESS) { return ret; } PackDtlsMsgHeader(type, sequence, totalLen - DTLS_HS_MSG_HEADER_SIZE, dtlsHeaderBuf); return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_TLS_BASIC int32_t Tls12PackMsg(TLS_Ctx *ctx, HS_MsgType type) { int32_t ret = HITLS_SUCCESS; if (type > HS_MSG_TYPE_END) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16943, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "type err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG); return HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG; } PackPacket pkt = {.buf = &ctx->hsCtx->msgBuf, .bufLen = &ctx->hsCtx->bufferLen, .bufOffset = &ctx->hsCtx->msgLen}; ret = PackAppendUint8ToBuf(&pkt, (uint8_t)type & 0xffu); /* Fill handshake message type */ if (ret != HITLS_SUCCESS) { return ret; } uint32_t msgLenPosition = 0u; ret = PackStartLengthField(&pkt, UINT24_SIZE, &msgLenPosition); if (ret != HITLS_SUCCESS) { return ret; } ret = PackHsMsgBody(ctx, type, &pkt); if (ret != HITLS_SUCCESS) { return ret; } PackCloseUint24Field(&pkt, msgLenPosition); /* Fill handshake message body length */ return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13PackMsg(TLS_Ctx *ctx, HS_MsgType type) { int32_t ret = HITLS_SUCCESS; int32_t enumBorder = HS_MSG_TYPE_END; if ((int32_t)type > enumBorder) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16944, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "type err", 0, 0, 0, 0); return HITLS_PACK_UNSUPPORT_HANDSHAKE_MSG; } HS_Ctx *hsCtx = ctx->hsCtx; PackPacket pkt = {.buf = &hsCtx->msgBuf, .bufLen = &hsCtx->bufferLen, .bufOffset = &hsCtx->msgLen}; ret = PackAppendUint8ToBuf(&pkt, (uint8_t)type & 0xffu); /* Fill handshake message type */ if (ret != HITLS_SUCCESS) { return ret; } uint32_t msgLenPosition = 0u; ret = PackStartLengthField(&pkt, UINT24_SIZE, &msgLenPosition); if (ret != HITLS_SUCCESS) { return ret; } ret = PackTls13HsMsgBody(ctx, type, &pkt); if (ret != HITLS_SUCCESS) { return ret; } PackCloseUint24Field(&pkt, msgLenPosition); /* Fill handshake message body length */ return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t HS_PackMsg(TLS_Ctx *ctx, HS_MsgType type) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15814, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the input parameter pointer is null.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } uint32_t version = HS_GetVersion(ctx); switch (version) { #ifdef HITLS_TLS_PROTO_TLS_BASIC case HITLS_VERSION_TLS12: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_VERSION_TLCP_DTLCP11: #if defined(HITLS_TLS_PROTO_DTLCP11) if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return Dtls12PackMsg(ctx, type); } #endif #endif return Tls12PackMsg(ctx, type); #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 case HITLS_VERSION_TLS13: return Tls13PackMsg(ctx, type); #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_DTLS12 case HITLS_VERSION_DTLS12: return Dtls12PackMsg(ctx, type); #endif default: break; } BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15815, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack handshake msg error, unsupport version[0x%x].", version, 0, 0, 0); return HITLS_PACK_UNSUPPORT_VERSION; }
2301_79861745/bench_create
tls/handshake/pack/src/pack.c
C
unknown
8,891
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_build.h" #include "securec.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 "cert.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_extensions.h" #include "pack_common.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t PackCertificate(TLS_Ctx *ctx, PackPacket *pkt) { /* Start packing certificate list length */ uint32_t certListLenPosition = 0u; int32_t ret = PackStartLengthField(pkt, CERT_LEN_TAG_SIZE, &certListLenPosition); if (ret != HITLS_SUCCESS) { return ret; } /* Certificate content using callback */ ret = SAL_CERT_EncodeCertChain(ctx, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15809, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode cert list fail.", 0, 0, 0, 0); return ret; } /* Close certificate list length field */ PackCloseUint24Field(pkt, certListLenPosition); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13PackCertificate(TLS_Ctx *ctx, PackPacket *pkt) { /* Pack the length of certificate_request_context */ int32_t ret = PackAppendUint8ToBuf(pkt, (uint8_t)ctx->certificateReqCtxSize); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the content of certificate_request_context */ if (ctx->certificateReqCtxSize > 0) { ret = PackAppendDataToBuf(pkt, ctx->certificateReqCtx, ctx->certificateReqCtxSize); if (ret != HITLS_SUCCESS) { return ret; } } /* Start packing certificate list length */ uint32_t certListLenPosition = 0u; ret = PackStartLengthField(pkt, CERT_LEN_TAG_SIZE, &certListLenPosition); if (ret != HITLS_SUCCESS) { return ret; } /* Certificate content using callback */ ret = SAL_CERT_EncodeCertChain(ctx, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15811, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode cert list fail when pack certificate msg.", 0, 0, 0, 0); return ret; } /* Close certificate list length field */ PackCloseUint24Field(pkt, certListLenPosition); return HITLS_SUCCESS; } #endif
2301_79861745/bench_create
tls/handshake/pack/src/pack_certificate.c
C
unknown
2,973
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #include <stdint.h> #include <stdbool.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 "tls.h" #include "hs_common.h" #include "hs_ctx.h" #include "hs_extensions.h" #include "pack_common.h" #include "pack_extensions.h" #include "cert_mgr_ctx.h" #include "custom_extensions.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) typedef struct { uint8_t certType; bool isSupported; } PackCertTypesInfo; static int32_t PackCertificateTypes(const TLS_Ctx *ctx, PackPacket *pkt) { const TLS_Config *config = &(ctx->config.tlsConfig); if ((config->cipherSuites == NULL) || (config->cipherSuitesSize == 0)) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15682, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack certificate types error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } PackCertTypesInfo certTypeLists[] = { {CERT_TYPE_RSA_SIGN, false}, {CERT_TYPE_ECDSA_SIGN, false}, {CERT_TYPE_DSS_SIGN, false} }; uint8_t certTypeListsSize = (uint8_t)(sizeof(certTypeLists) / sizeof(certTypeLists[0])); uint8_t supportedCertTypesSize = 0; uint32_t baseSignAlgorithmsSize = config->signAlgorithmsSize; const uint16_t *baseSignAlgorithms = config->signAlgorithms; for (uint32_t i = 0; i < baseSignAlgorithmsSize; i++) { HITLS_CERT_KeyType keyType = SAL_CERT_SignScheme2CertKeyType(ctx, baseSignAlgorithms[i]); CERT_Type certType = CertKeyType2CertType(keyType); for (uint32_t j = 0; j < certTypeListsSize; j++) { if ((certTypeLists[j].certType == certType) && (certTypeLists[j].isSupported == false)) { certTypeLists[j].isSupported = true; supportedCertTypesSize++; break; } } } int32_t ret = PackAppendUint8ToBuf(pkt, supportedCertTypesSize); if (ret != HITLS_SUCCESS) { return ret; } for (uint32_t i = 0; i < certTypeListsSize; i++) { if (certTypeLists[i].isSupported == true) { ret = PackAppendUint8ToBuf(pkt, certTypeLists[i].certType); if (ret != HITLS_SUCCESS) { return ret; } } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #if defined(HITLS_TLS_PROTO_TLS12) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t PackSignAlgorithms(const TLS_Ctx *ctx, PackPacket *pkt) { const TLS_Config *config = &(ctx->config.tlsConfig); if ((config->signAlgorithms == NULL) || (config->signAlgorithmsSize == 0)) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15684, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack signature algorithms error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } uint16_t signAlgorithmsSize = (uint16_t)config->signAlgorithmsSize * sizeof(uint16_t); int32_t ret = PackAppendUint16ToBuf(pkt, signAlgorithmsSize); if (ret != HITLS_SUCCESS) { return ret; } for (uint32_t index = 0; index < config->signAlgorithmsSize; index++) { ret = PackAppendUint16ToBuf(pkt, config->signAlgorithms[index]); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS12 || HITLS_TLS_PROTO_DTLS12 */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t PackCALists(const TLS_Ctx *ctx, PackPacket *pkt) { const TLS_Config *config = &(ctx->config.tlsConfig); if (config->caList == NULL) { return PackAppendUint16ToBuf(pkt, 0); } #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES uint32_t caListLenPosition = 0u; int32_t ret = PackStartLengthField(pkt, sizeof(uint16_t), &caListLenPosition); if (ret != HITLS_SUCCESS) { return ret; } ret = PackTrustedCAList(config->caList, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17370, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack CA list error", 0, 0, 0, 0); return ret; } PackCloseUint16Field(pkt, caListLenPosition); #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ return HITLS_SUCCESS; } int32_t PackCertificateRequest(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = PackCertificateTypes(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_TLS_PROTO_TLS12) || defined(HITLS_TLS_PROTO_DTLS12) /* TLCP does not have the signature algorithm field */ if (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11) { ret = PackSignAlgorithms(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } } #endif ret = PackCALists(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t PackSignAlgorithmsExtension(const TLS_Ctx *ctx, PackPacket *pkt) { const TLS_Config *config = &(ctx->config.tlsConfig); if ((config->signAlgorithms == NULL) || (config->signAlgorithmsSize == 0)) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15686, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack signature algorithms error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } uint32_t signAlgorithmsSize = 0; uint16_t *signAlgorithms = CheckSupportSignAlgorithms(ctx, config->signAlgorithms, config->signAlgorithmsSize, &signAlgorithmsSize); if (signAlgorithms == NULL || signAlgorithmsSize == 0) { BSL_SAL_FREE(signAlgorithms); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17310, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "no available signAlgo", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH; } uint16_t exMsgHeaderLen = sizeof(uint16_t); uint16_t exMsgDataLen = sizeof(uint16_t) * (uint16_t)signAlgorithmsSize; int32_t ret = PackExtensionHeader(HS_EX_TYPE_SIGNATURE_ALGORITHMS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(signAlgorithms); return ret; } (void)PackAppendUint16ToBuf(pkt, exMsgDataLen); for (uint32_t index = 0; index < signAlgorithmsSize; index++) { (void)PackAppendUint16ToBuf(pkt, signAlgorithms[index]); } BSL_SAL_FREE(signAlgorithms); return HITLS_SUCCESS; } static int32_t PackCertReqExtensions(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; const PackExtInfo extMsgList[] = { {.exMsgType = HS_EX_TYPE_SIGNATURE_ALGORITHMS, .needPack = true, .packFunc = PackSignAlgorithmsExtension}, {.exMsgType = HS_EX_TYPE_SIGNATURE_ALGORITHMS_CERT, .needPack = false, .packFunc = NULL}, #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES {.exMsgType = HS_EX_TYPE_CERTIFICATE_AUTHORITIES, .needPack = ctx->config.tlsConfig.caList != NULL, .packFunc = PackClientCAList}, #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ }; uint32_t listSize = sizeof(extMsgList) / sizeof(extMsgList[0]); #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsPackNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST)) { ret = PackCustomExtensions(ctx, pkt, HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST, NULL, 0); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ for (uint32_t index = 0; index < listSize; index++) { if (extMsgList[index].packFunc == NULL) { ret = PackEmptyExtension(extMsgList[index].exMsgType, extMsgList[index].needPack, pkt); if (ret != HITLS_SUCCESS) { return ret; } } if (extMsgList[index].packFunc != NULL && extMsgList[index].needPack) { ret = extMsgList[index].packFunc(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } } } return HITLS_SUCCESS; } int32_t Tls13PackCertReqExtensions(const TLS_Ctx *ctx, PackPacket *pkt) { /* Start packing extensions length */ uint32_t extensionsLenPosition = 0u; int32_t ret = PackStartLengthField(pkt, sizeof(uint16_t), &extensionsLenPosition); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the extended content of the Tls1.3 Certificate Request */ ret = PackCertReqExtensions(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Close extensions length field */ PackCloseUint16Field(pkt, extensionsLenPosition); return HITLS_SUCCESS; } int32_t Tls13PackCertificateRequest(const TLS_Ctx *ctx, PackPacket *pkt) { /* Pack certificate_request_context length */ int32_t ret = PackAppendUint8ToBuf(pkt, (uint8_t)ctx->certificateReqCtxSize); if (ret != HITLS_SUCCESS) { return ret; } /* Pack certificate_request_context content */ if (ctx->certificateReqCtxSize > 0) { ret = PackAppendDataToBuf(pkt, ctx->certificateReqCtx, ctx->certificateReqCtxSize); if (ret != HITLS_SUCCESS) { return ret; } } ret = Tls13PackCertReqExtensions(ctx, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15690, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack tls1.3 certificate request msg extension content fail.", 0, 0, 0, 0); return ret; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/pack/src/pack_certificate_request.c
C
unknown
10,662
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT) || defined(HITLS_TLS_PROTO_TLS13) #include <stdint.h> #include "securec.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 "pack_common.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" int32_t PackCertificateVerify(const TLS_Ctx *ctx, PackPacket *pkt) { const HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; int32_t ret = HITLS_SUCCESS; if (hsCtx->verifyCtx->verifyDataSize == 0u) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15824, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the verify data is illegal.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } #if defined(HITLS_TLS_PROTO_TLS12) || defined(HITLS_TLS_PROTO_DTLS12) || defined(HITLS_TLS_PROTO_TLS13) if (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11) { ret = PackAppendUint16ToBuf(pkt, (uint16_t)ctx->negotiatedInfo.signScheme); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* Pack signature data length */ ret = PackAppendUint16ToBuf(pkt, (uint16_t)hsCtx->verifyCtx->verifyDataSize); if (ret != HITLS_SUCCESS) { return ret; } /* Pack signature data */ return PackAppendDataToBuf(pkt, hsCtx->verifyCtx->verifyData, hsCtx->verifyCtx->verifyDataSize); } #endif /* HITLS_TLS_HOST_CLIENT || HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/pack/src/pack_certificate_verify.c
C
unknown
2,056
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #include <stdint.h> #include "securec.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "tls.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_security.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "cipher_suite.h" #include "hs_ctx.h" #include "pack_common.h" #include "pack_extensions.h" #include "hs_common.h" #define CIPHER_SUITES_LEN_SIZE 2u // Pack the version content of the client Hello message. static int32_t PackClientVersion(const TLS_Ctx *ctx, uint16_t version, PackPacket *pkt) { (void)ctx; #ifdef HITLS_TLS_FEATURE_SECURITY const TLS_Config *tlsConfig = &ctx->config.tlsConfig; int32_t ret = SECURITY_CfgCheck((const HITLS_Config *)tlsConfig, HITLS_SECURITY_SECOP_VERSION, 0, version, NULL); if (ret != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16924, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CfgCheck fail, ret %d", ret, 0, 0, 0); ctx->method.sendAlert((TLS_Ctx *)(uintptr_t)ctx, ALERT_LEVEL_FATAL, ALERT_INSUFFICIENT_SECURITY); BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSECURE_VERSION); return HITLS_PACK_UNSECURE_VERSION; } #endif /* HITLS_TLS_FEATURE_SECURITY */ return PackAppendUint16ToBuf(pkt, version); } #ifdef HITLS_TLS_PROTO_DTLS12 // Pack the cookie content of the client Hello message. static int32_t PackClientCookie(PackPacket *pkt, const uint8_t *cookie, uint8_t cookieLen) { int32_t ret = PackAppendUint8ToBuf(pkt, cookieLen); if (ret != HITLS_SUCCESS) { return ret; } if (cookieLen == 0u) { return HITLS_SUCCESS; } return PackAppendDataToBuf(pkt, cookie, cookieLen); } #endif /* HITLS_TLS_PROTO_DTLS12 */ static int32_t PackCipherSuites(const TLS_Ctx *ctx, PackPacket *pkt, bool isTls13) { uint16_t *cipherSuites = NULL; uint32_t cipherSuitesSize = 0; #ifdef HITLS_TLS_PROTO_TLS13 if (isTls13) { cipherSuites = ctx->config.tlsConfig.tls13CipherSuites; cipherSuitesSize = ctx->config.tlsConfig.tls13cipherSuitesSize; } else { cipherSuites = ctx->config.tlsConfig.cipherSuites; cipherSuitesSize = ctx->config.tlsConfig.cipherSuitesSize; } #else (void)isTls13; cipherSuites = ctx->config.tlsConfig.cipherSuites; cipherSuitesSize = ctx->config.tlsConfig.cipherSuitesSize; #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t ret = HITLS_SUCCESS; for (uint32_t i = 0; i < cipherSuitesSize; i++) { if (!IsCipherSuiteAllowed(ctx, cipherSuites[i])) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15845, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "The cipher suite [0x%04x] is NOT supported, index=[%u].", cipherSuites[i], i, 0, 0); continue; } ret = PackAppendUint16ToBuf(pkt, cipherSuites[i]); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } static int32_t PackScsvCipherSuites(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; /* If the local is not in the renegotiation state, the SCSV algorithm set needs to be packed. */ if (!ctx->negotiatedInfo.isRenegotiation) { ret = PackAppendUint16ToBuf(pkt, TLS_EMPTY_RENEGOTIATION_INFO_SCSV); if (ret != HITLS_SUCCESS) { return ret; } } #ifdef HITLS_TLS_FEATURE_MODE_FALL_BACK_SCSV if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_SEND_FALLBACK_SCSV) != 0) { ret = PackAppendUint16ToBuf(pkt, TLS_FALLBACK_SCSV); if (ret != HITLS_SUCCESS) { return ret; } } #endif return HITLS_SUCCESS; } // Pack the cipher suites content of the client hello message. static int32_t PackClientCipherSuites(const TLS_Ctx *ctx, PackPacket *pkt) { uint32_t cipherLenPosition = 0u; /* Finally fill in the length of the cipher suites */ int32_t ret = PackStartLengthField(pkt, CIPHER_SUITES_LEN_SIZE, &cipherLenPosition); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13) { ret = PackCipherSuites(ctx, pkt, 1); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16925, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PackCipherSuites fail", 0, 0, 0, 0); return ret; } } #endif /* HITLS_TLS_PROTO_TLS13 */ if (ctx->config.tlsConfig.minVersion != HITLS_VERSION_TLS13) { ret = PackCipherSuites(ctx, pkt, 0); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16926, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PackCipherSuites fail", 0, 0, 0, 0); return ret; } } uint32_t suitesLength = 0; ret = PackGetSubBuffer(pkt, cipherLenPosition, &suitesLength, NULL); if (ret != HITLS_SUCCESS) { return ret; } if (suitesLength == CIPHER_SUITES_LEN_SIZE) { BSL_ERR_PUSH_ERROR(HITLS_PACK_CLIENT_CIPHER_SUITE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15732, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack cipher suite error, no cipher suite.", 0, 0, 0, 0); return HITLS_PACK_CLIENT_CIPHER_SUITE_ERR; } ret = PackScsvCipherSuites(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* The cipher suite has been filled. Each cipher suite takes two bytes, so the length of the filled cipher suite can * be calculated according to offset */ PackCloseUint16Field(pkt, cipherLenPosition); return HITLS_SUCCESS; } // Pack the content of the method for compressing the client Hello message. static int32_t PackClientCompressionMethod(PackPacket *pkt) { int32_t ret = PackAppendUint8ToBuf(pkt, 1); if (ret != HITLS_SUCCESS) { return ret; } /* Compression methods Currently support uncompressed */ return PackAppendUint8ToBuf(pkt, 0); } // Pack the session and cookie content of the client hello message. static int32_t PackSessionAndCookie(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; (void)ret; (void)ctx; #if defined(HITLS_TLS_FEATURE_SESSION_ID) || defined(HITLS_TLS_PROTO_TLS13) HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; ret = PackSessionId(pkt, hsCtx->sessionId, hsCtx->sessionIdSize); if (ret != HITLS_SUCCESS) { (void)memset_s(hsCtx->sessionId, hsCtx->sessionIdSize, 0, hsCtx->sessionIdSize); return ret; } #else // Session recovery is not supported. /* SessionId (Session is not supported yet and the length field is initialized with a value of 0) */ ret = PackAppendUint8ToBuf(pkt, 0); if (ret != HITLS_SUCCESS) { return ret; } #endif #ifdef HITLS_TLS_PROTO_DTLS12 const TLS_Config *tlsConfig = &ctx->config.tlsConfig; if (IS_SUPPORT_DATAGRAM(tlsConfig->originVersionMask)) { ret = PackClientCookie(pkt, ctx->negotiatedInfo.cookie, (uint8_t)ctx->negotiatedInfo.cookieSize); if (ret != HITLS_SUCCESS) { (void)memset_s(ctx->negotiatedInfo.cookie, ctx->negotiatedInfo.cookieSize, 0, ctx->negotiatedInfo.cookieSize); return ret; } } #endif return HITLS_SUCCESS; } // Pack the mandatory content of the ClientHello message. static int32_t PackClientHelloMandatoryField(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; const TLS_Config *tlsConfig = &ctx->config.tlsConfig; if (ctx->hsCtx->clientRandom == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16927, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "clientRandom null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } uint16_t version = #ifdef HITLS_TLS_PROTO_TLS13 (tlsConfig->maxVersion == HITLS_VERSION_TLS13) ? HITLS_VERSION_TLS12 : #endif tlsConfig->maxVersion; ret = PackClientVersion(ctx, version, pkt); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendDataToBuf(pkt, ctx->hsCtx->clientRandom, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { return ret; } ret = PackSessionAndCookie(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } ret = PackClientCipherSuites(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } return PackClientCompressionMethod(pkt); } // Pack the ClientHello message to form the Handshake body. int32_t PackClientHello(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = PackClientHelloMandatoryField(ctx, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15735, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack client hello mandatory content fail.", 0, 0, 0, 0); return ret; } ret = PackClientExtension(ctx, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15736, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack client hello extension content fail.", 0, 0, 0, 0); return ret; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/pack/src/pack_client_hello.c
C
unknown
9,781
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include <stdint.h> #include "securec.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 "bsl_sal.h" #include "hitls_error.h" #include "tls.h" #include "crypt.h" #include "cert_method.h" #include "hs_ctx.h" #include "hs_common.h" #include "pack_common.h" #ifdef HITLS_TLS_SUITE_KX_ECDHE #ifdef HITLS_TLS_PROTO_TLCP11 static int32_t PackDtlcpbytes(const TLS_Ctx *ctx, PackPacket *pkt) { /* Compatible with OpenSSL. Three bytes are added to the client key exchange. */ int32_t ret = HITLS_SUCCESS; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { ret = PackAppendUint8ToBuf(pkt, HITLS_EC_CURVE_TYPE_NAMED_CURVE); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendUint16ToBuf(pkt, HITLS_EC_GROUP_SM2); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #endif static int32_t PackClientKxMsgNamedCurve(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint32_t pubKeyLen; EcdhParam *ecdh = &(ctx->hsCtx->kxCtx->keyExchParam.ecdh); HITLS_ECParameters *curveParams = &ecdh->curveParams; KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; pubKeyLen = SAL_CRYPT_GetCryptLength(ctx, HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN, curveParams->param.namedcurve); if (pubKeyLen == 0u) { BSL_ERR_PUSH_ERROR(HITLS_PACK_INVALID_KX_PUBKEY_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15673, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid key exchange pubKey length.", 0, 0, 0, 0); return HITLS_PACK_INVALID_KX_PUBKEY_LENGTH; } #ifdef HITLS_TLS_PROTO_TLCP11 ret = PackDtlcpbytes(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } #endif uint32_t pubKeyLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint8_t), &pubKeyLenPosition); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *reservedBuf = NULL; ret = PackReserveBytes(pkt, pubKeyLen, &reservedBuf); if (ret != HITLS_SUCCESS) { return ret; } uint32_t pubKeyUsedLen = 0; ret = SAL_CRYPT_EncodeEcdhPubKey(kxCtx->key, reservedBuf, pubKeyLen, &pubKeyUsedLen); if (ret != HITLS_SUCCESS || pubKeyLen != pubKeyUsedLen) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15675, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode ecdh key fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } (void)PackSkipBytes(pkt, pubKeyUsedLen); PackCloseUint8Field(pkt, pubKeyLenPosition); return HITLS_SUCCESS; } static int32_t PackClientKxMsgEcdhe(const TLS_Ctx *ctx, PackPacket *pkt) { HITLS_ECCurveType type = ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type; switch (type) { case HITLS_EC_CURVE_TYPE_NAMED_CURVE: return PackClientKxMsgNamedCurve(ctx, pkt); default: break; } BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSUPPORT_KX_CURVE_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15676, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unsupport key exchange curve type.", 0, 0, 0, 0); return HITLS_PACK_UNSUPPORT_KX_CURVE_TYPE; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE static int32_t PackClientKxMsgDhe(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; DhParam *dh = &ctx->hsCtx->kxCtx->keyExchParam.dh; KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; uint32_t pubkeyLen = dh->plen; if (pubkeyLen == 0u) { BSL_ERR_PUSH_ERROR(HITLS_PACK_INVALID_KX_PUBKEY_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15677, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid key exchange pubKey length.", 0, 0, 0, 0); return HITLS_PACK_INVALID_KX_PUBKEY_LENGTH; } uint32_t pubKeyLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint16_t), &pubKeyLenPosition); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *reservedBuf = NULL; ret = PackReserveBytes(pkt, pubkeyLen, &reservedBuf); if (ret != HITLS_SUCCESS) { return ret; } /* fill pubkey */ ret = SAL_CRYPT_EncodeDhPubKey(kxCtx->key, reservedBuf, pubkeyLen, &pubkeyLen); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_DH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15679, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode dh pub key fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_DH_KEY; } ret = PackSkipBytes(pkt, pubkeyLen); if (ret != HITLS_SUCCESS) { return ret; } PackCloseUint16Field(pkt, pubKeyLenPosition); return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_RSA int32_t PackClientKxMsgRsa(TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; KeyExchCtx *kxCtx = hsCtx->kxCtx; uint8_t *preMasterSecret = kxCtx->keyExchParam.rsa.preMasterSecret; uint32_t encLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint16_t), &encLenPosition); if (ret != HITLS_SUCCESS) { return ret; } HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *mgrCtx = config->certMgrCtx; HITLS_CERT_X509 *cert = SAL_CERT_PairGetX509(hsCtx->peerCert); HITLS_CERT_Key *pubkey = NULL; ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16929, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CERT_CTRL_GET_PUB_KEY fail", 0, 0, 0, 0); return ret; } /* Use CERT_KEY_CTRL_GET_SIGN_LEN to get encrypt length(Only by RSA and ECC) */ uint32_t encryptLen = MAX_SIGN_SIZE; uint8_t *encBuf = NULL; ret = PackReserveBytes(pkt, encryptLen, &encBuf); if (ret != HITLS_SUCCESS) { SAL_CERT_KeyFree(mgrCtx, pubkey); return ret; } uint32_t encLen = encryptLen; ret = SAL_CERT_KeyEncrypt(ctx, pubkey, preMasterSecret, MASTER_SECRET_LEN, encBuf, &encLen); SAL_CERT_KeyFree(mgrCtx, pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16930, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "KeyEncrypt fail", 0, 0, 0, 0); return ret; } ret = PackSkipBytes(pkt, encLen); if (ret != HITLS_SUCCESS) { return ret; } PackCloseUint16Field(pkt, encLenPosition); return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_PROTO_TLCP11 static int32_t PackClientKxMsgEcc(TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; KeyExchCtx *kxCtx = hsCtx->kxCtx; uint8_t *preMasterSecret = kxCtx->keyExchParam.ecc.preMasterSecret; uint32_t encLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint16_t), &encLenPosition); if (ret != HITLS_SUCCESS) { return ret; } /* Encrypt the PreMasterSecret using the public key of the server certificate */ HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *certMgrCtx = config->certMgrCtx; HITLS_CERT_X509 *certEnc = SAL_CERT_GetTlcpEncCert(hsCtx->peerCert); HITLS_CERT_Key *pubkey = NULL; ret = SAL_CERT_X509Ctrl(config, certEnc, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16218, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get encrypt cert public key failed.", 0, 0, 0, 0); return ret; } /* Use CERT_KEY_CTRL_GET_SIGN_LEN to get encrypt length(Only by RSA and ECC) */ uint32_t encryptLen = MAX_SIGN_SIZE; uint8_t *encBuf = NULL; ret = PackReserveBytes(pkt, encryptLen, &encBuf); if (ret != HITLS_SUCCESS) { SAL_CERT_KeyFree(certMgrCtx, pubkey); return ret; } uint32_t encLen = encryptLen; ret = SAL_CERT_KeyEncrypt(ctx, pubkey, preMasterSecret, MASTER_SECRET_LEN, encBuf, &encLen); SAL_CERT_KeyFree(certMgrCtx, pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16932, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "KeyEncrypt fail", 0, 0, 0, 0); return ret; } ret = PackSkipBytes(pkt, encLen); if (ret != HITLS_SUCCESS) { return ret; } PackCloseUint16Field(pkt, encLenPosition); return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_PSK static int32_t PackClientKxMsgIdentity(const TLS_Ctx *ctx, PackPacket *pkt) { uint8_t *pskIdentity = ctx->hsCtx->kxCtx->pskInfo->identity; uint32_t pskIdentitySize = ctx->hsCtx->kxCtx->pskInfo->identityLen; /* append identity */ int32_t ret = PackAppendUint16ToBuf(pkt, (uint16_t)pskIdentitySize); if (ret != HITLS_SUCCESS) { return ret; } if (pskIdentitySize > 0) { ret = PackAppendDataToBuf(pkt, pskIdentity, pskIdentitySize); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PSK */ // Pack the ClientKeyExchange message. int32_t PackClientKeyExchange(TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_PSK /* PSK negotiation pre act: append identity */ if (IsPskNegotiation(ctx)) { ret = PackClientKxMsgIdentity(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_PSK */ /* Pack the key exchange message */ switch (ctx->negotiatedInfo.cipherSuiteInfo.kxAlg) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: /* TLCP is also included */ case HITLS_KEY_EXCH_ECDHE_PSK: ret = PackClientKxMsgEcdhe(ctx, pkt); break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = PackClientKxMsgDhe(ctx, pkt); break; #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_RSA case HITLS_KEY_EXCH_RSA: case HITLS_KEY_EXCH_RSA_PSK: ret = PackClientKxMsgRsa(ctx, pkt); break; #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: ret = PackClientKxMsgEcc(ctx, pkt); break; #endif case HITLS_KEY_EXCH_PSK: ret = HITLS_SUCCESS; break; default: BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSUPPORT_KX_ALG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15681, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unsupport key exchange algorithm when pack client key exchange.", 0, 0, 0, 0); return HITLS_PACK_UNSUPPORT_KX_ALG; } return ret; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/pack/src/pack_client_key_exchange.c
C
unknown
11,712
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include "hitls_build.h" #include "securec.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hs_msg.h" #include "hs_ctx.h" #include "hitls_cert_type.h" #include "bsl_list.h" #include "pack_common.h" #define BUFFER_GROW_FACTOR 2u #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Pack the packet header. * * @param type [IN] message type * @param sequence [IN] Sequence number (dedicated for DTLS) * @param length [IN] message body length * @param buf [OUT] message header */ void PackDtlsMsgHeader(HS_MsgType type, uint16_t sequence, uint32_t length, uint8_t *buf) { buf[0] = (uint8_t)type & 0xffu; /** Type of the handshake message */ BSL_Uint24ToByte(length, &buf[DTLS_HS_MSGLEN_ADDR]); /** Fills the length of the handshake message */ BSL_Uint16ToByte( sequence, &buf[DTLS_HS_MSGSEQ_ADDR]); /** The 2 bytes starting from the 4th byte are the sn of the message */ BSL_Uint24ToByte( 0, &buf[DTLS_HS_FRAGMENT_OFFSET_ADDR]); /** The 3 bytes starting from the 6th byte are the fragment offset. */ BSL_Uint24ToByte( length, &buf[DTLS_HS_FRAGMENT_LEN_ADDR]); /** The 3 bytes starting from the 9th byte are the fragment length. */ } #endif /* HITLS_TLS_PROTO_DTLS12 */ #if defined(HITLS_TLS_FEATURE_SESSION_ID) || defined(HITLS_TLS_PROTO_TLS13) /** * @brief Pack the message session ID. * * @param id [IN] Session ID * @param idSize [IN] Session ID length * @param buf [OUT] message buffer * @param bufLen [IN] Maximum message length * @param usedLen [OUT] Length of the packed message * * @retval HITLS_SUCCESS Assembly succeeded. * @retval HITLS_PACK_SESSIONID_ERR Failed to pack the sessionId. * @retval HITLS_MEMCPY_FAIL Memory Copy Failure */ int32_t PackSessionId(PackPacket *pkt, const uint8_t *id, uint32_t idSize) { /* If the sessionId length does not meet the requirement, an error code is returned */ if ((idSize != 0) && ((idSize > TLS_HS_MAX_SESSION_ID_SIZE) || (idSize < TLS_HS_MIN_SESSION_ID_SIZE))) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SESSIONID_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15849, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "session id size is incorrect when pace session id.", 0, 0, 0, 0); return HITLS_PACK_SESSIONID_ERR; } int32_t ret = PackAppendUint8ToBuf(pkt, (uint8_t)idSize); if (ret != HITLS_SUCCESS) { return ret; } /* If the value of sessionId is 0, a success message is returned */ if (idSize == 0u) { return HITLS_SUCCESS; } return PackAppendDataToBuf(pkt, id, idSize); } #endif /* #if HITLS_TLS_FEATURE_SESSION_ID || HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES int32_t PackTrustedCAList(HITLS_TrustedCAList *caList, PackPacket *pkt) { if (caList == NULL) { return HITLS_NULL_INPUT; } int32_t ret = HITLS_SUCCESS; HITLS_TrustedCANode *node = (HITLS_TrustedCANode *)BSL_LIST_GET_FIRST(caList); while (node != NULL) { if (node->data != NULL && node->dataSize != 0) { ret = PackAppendUint16ToBuf(pkt, (uint16_t)node->dataSize); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendDataToBuf(pkt, node->data, node->dataSize); if (ret != HITLS_SUCCESS) { return ret; } } node = (HITLS_TrustedCANode *)BSL_LIST_GET_NEXT(caList); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ static int32_t PackMsBufferGrow(PackPacket *pkt, uint32_t newSize) { uint32_t oldDataSize = *pkt->bufLen; uint8_t *newAddr = BSL_SAL_Realloc(*pkt->buf, newSize, oldDataSize); if (newAddr == NULL) { return HITLS_MEMALLOC_FAIL; } *pkt->buf = newAddr; *pkt->bufLen = newSize; return HITLS_SUCCESS; } static int32_t PackMsBufferPrepare(PackPacket *pkt, uint32_t msgSize) { if (*pkt->bufLen - *pkt->bufOffset >= msgSize) { return HITLS_SUCCESS; } if (HITLS_HS_BUFFER_SIZE_LIMIT - *pkt->bufOffset < msgSize) { return HITLS_PACK_NOT_ENOUGH_BUF_LENGTH; } uint32_t oldBufSize = *pkt->bufLen; uint32_t newBufSize = (msgSize > oldBufSize) ? msgSize : oldBufSize; if (newBufSize >= HITLS_HS_BUFFER_SIZE_LIMIT / BUFFER_GROW_FACTOR) { newBufSize = HITLS_HS_BUFFER_SIZE_LIMIT; } else { newBufSize = newBufSize * BUFFER_GROW_FACTOR; } return PackMsBufferGrow(pkt, newBufSize); } int32_t PackAppendUint8ToBuf(PackPacket *pkt, uint8_t value) { int32_t ret = PackMsBufferPrepare(pkt, sizeof(uint8_t)); if (ret != HITLS_SUCCESS) { return ret; } (*pkt->buf)[*pkt->bufOffset] = value; *pkt->bufOffset += sizeof(uint8_t); return HITLS_SUCCESS; } int32_t PackAppendUint16ToBuf(PackPacket *pkt, uint16_t value) { int32_t ret = PackMsBufferPrepare(pkt, sizeof(uint16_t)); if (ret != HITLS_SUCCESS) { return ret; } BSL_Uint16ToByte(value, &(*pkt->buf)[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); return HITLS_SUCCESS; } int32_t PackAppendUint24ToBuf(PackPacket *pkt, uint32_t value) { int32_t ret = PackMsBufferPrepare(pkt, UINT24_SIZE); if (ret != HITLS_SUCCESS) { return ret; } BSL_Uint24ToByte(value, &(*pkt->buf)[*pkt->bufOffset]); *pkt->bufOffset += UINT24_SIZE; return HITLS_SUCCESS; } int32_t PackAppendUint32ToBuf(PackPacket *pkt, uint32_t value) { int32_t ret = PackMsBufferPrepare(pkt, sizeof(uint32_t)); if (ret != HITLS_SUCCESS) { return ret; } BSL_Uint32ToByte(value, &(*pkt->buf)[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint32_t); return HITLS_SUCCESS; } int32_t PackAppendUint64ToBuf(PackPacket *pkt, uint64_t value) { int32_t ret = PackMsBufferPrepare(pkt, sizeof(uint64_t)); if (ret != HITLS_SUCCESS) { return ret; } BSL_Uint64ToByte(value, &(*pkt->buf)[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint64_t); return HITLS_SUCCESS; } int32_t PackAppendDataToBuf(PackPacket *pkt, const uint8_t *data, uint32_t size) { int32_t ret = PackMsBufferPrepare(pkt, size); if (ret != HITLS_SUCCESS) { return ret; } (void)memcpy_s(&(*pkt->buf)[*pkt->bufOffset], *pkt->bufLen - *pkt->bufOffset, data, size); *pkt->bufOffset += size; return HITLS_SUCCESS; } int32_t PackReserveBytes(PackPacket *pkt, uint32_t size, uint8_t **buf) { int32_t ret = PackMsBufferPrepare(pkt, size); if (ret != HITLS_SUCCESS) { return ret; } if (buf != NULL) { *buf = &(*pkt->buf)[*pkt->bufOffset]; } return HITLS_SUCCESS; } int32_t PackStartLengthField(PackPacket *pkt, uint32_t size, uint32_t *allocatedPosition) { int32_t ret = PackMsBufferPrepare(pkt, size); if (ret != HITLS_SUCCESS) { return ret; } *allocatedPosition = *pkt->bufOffset; *pkt->bufOffset += size; return HITLS_SUCCESS; } int32_t PackSkipBytes(PackPacket *pkt, uint32_t size) { if (*pkt->bufLen - *pkt->bufOffset < size) { return HITLS_PACK_NOT_ENOUGH_BUF_LENGTH; } *pkt->bufOffset += size; return HITLS_SUCCESS; } void PackCloseUint8Field(PackPacket *pkt, uint32_t position) { (*pkt->buf)[position] = (uint8_t)(*pkt->bufOffset - position - sizeof(uint8_t)); return; } void PackCloseUint16Field(PackPacket *pkt, uint32_t position) { BSL_Uint16ToByte((uint16_t)(*pkt->bufOffset - position - sizeof(uint16_t)), &(*pkt->buf)[position]); return; } void PackCloseUint24Field(PackPacket *pkt, uint32_t position) { BSL_Uint24ToByte((uint32_t)(*pkt->bufOffset - position - UINT24_SIZE), &(*pkt->buf)[position]); return; } int32_t PackGetSubBuffer(PackPacket *pkt, uint32_t start, uint32_t *length, uint8_t **buf) { if (length == NULL) { return HITLS_NULL_INPUT; } if (start > *pkt->bufOffset) { return HITLS_PACK_NOT_ENOUGH_BUF_LENGTH; } *length = *pkt->bufOffset - start; if (buf != NULL) { *buf = &(*pkt->buf)[start]; } return HITLS_SUCCESS; }
2301_79861745/bench_create
tls/handshake/pack/src/pack_common.c
C
unknown
8,785
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef PACK_COMMON_H #define PACK_COMMON_H #include <stdint.h> #include "tls.h" #include "pack.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Pack session ID * * @param pkt [IN/OUT] Context for packing * @param id [IN] Session ID * @param idSize [IN] Session ID length * * @retval HITLS_SUCCESS * @retval HITLS_PACK_SESSIONID_ERR Failed to pack sessionId * @retval HITLS_MEMALLOC_FAIL Grow buffer failed * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH Buffer is not enough */ int32_t PackSessionId(PackPacket *pkt, const uint8_t *id, uint32_t idSize); /** * @brief Pack DTLS message header * * @param type [IN] Message type * @param sequence [IN] Sequence number (only in DTLS) * @param length [IN] Length of message body * @param buf [OUT] Message header */ void PackDtlsMsgHeader(HS_MsgType type, uint16_t sequence, uint32_t length, uint8_t *buf); int32_t PackTrustedCAList(HITLS_TrustedCAList *caList, PackPacket *pkt); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end PACK_COMMON_H */
2301_79861745/bench_create
tls/handshake/pack/src/pack_common.h
C
unknown
1,617
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_TLS13) && defined(HITLS_TLS_HOST_SERVER) #include <stdint.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 "tls.h" #include "hs_ctx.h" #include "hs_extensions.h" #include "pack_common.h" #include "pack_extensions.h" #include "custom_extensions.h" static int32_t PackEncryptedSupportedGroups(const TLS_Ctx *ctx, PackPacket *pkt) { const TLS_Config *config = &(ctx->config.tlsConfig); if (config->groupsSize == 0 || config->groups == NULL) { return HITLS_SUCCESS; } /* Calculate the extension length */ uint16_t exMsgHeaderLen = sizeof(uint16_t); uint16_t exMsgDataLen = sizeof(uint16_t) * (uint16_t)config->groupsSize; /* Pack the extension header */ int32_t ret = PackExtensionHeader(HS_EX_TYPE_SUPPORTED_GROUPS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the extended support group */ (void)PackAppendUint16ToBuf(pkt, exMsgDataLen); for (uint32_t index = 0; index < config->groupsSize; index++) { (void)PackAppendUint16ToBuf(pkt, config->groups[index]); } return HITLS_SUCCESS; } /** * @brief Pack the Encrypted_extensions extension. * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS succeeded. * @retval For other error codes, see hitls_error.h. */ static int32_t PackEncryptedExs(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint32_t listSize; const PackExtInfo extMsgList[] = { {.exMsgType = HS_EX_TYPE_SUPPORTED_GROUPS, .needPack = true, .packFunc = PackEncryptedSupportedGroups}, {.exMsgType = HS_EX_TYPE_EARLY_DATA, /* This field is available only in 0-rrt mode */ .needPack = false, .packFunc = NULL}, #ifdef HITLS_TLS_FEATURE_SNI {.exMsgType = HS_EX_TYPE_SERVER_NAME, /* During extension, only empty SNI extensions are encapsulated. */ .needPack = ctx->negotiatedInfo.isSniStateOK, .packFunc = NULL}, #endif /* HITLS_TLS_FEATURE_SNI */ #ifdef HITLS_TLS_FEATURE_ALPN {.exMsgType = HS_EX_TYPE_APP_LAYER_PROTOCOLS, .needPack = (ctx->negotiatedInfo.alpnSelected != NULL), .packFunc = PackServerSelectAlpnProto}, #endif /* HITLS_TLS_FEATURE_ALPN */ }; #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsPackNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS)) { ret = PackCustomExtensions(ctx, pkt, HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS, NULL, 0); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ /* Calculate the number of extended types */ listSize = sizeof(extMsgList) / sizeof(extMsgList[0]); /* Pack the Server Hello extension */ for (uint32_t index = 0; index < listSize; index++) { if (extMsgList[index].needPack == false) { continue; } /* Empty extension */ if (extMsgList[index].packFunc == NULL) { ret = PackEmptyExtension(extMsgList[index].exMsgType, extMsgList[index].needPack, pkt); if (ret != HITLS_SUCCESS) { return ret; } } /* Non-empty extension */ if (extMsgList[index].packFunc != NULL) { ret = extMsgList[index].packFunc(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } } } return HITLS_SUCCESS; } /** * @brief Pack the Encrypted_extensions message. * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH The message buffer length is insufficient. */ int32_t PackEncryptedExtensions(const TLS_Ctx *ctx, PackPacket *pkt) { uint32_t extensionsLenPosition = 0u; /* Start packing extensions length field */ int32_t ret = PackStartLengthField(pkt, sizeof(uint16_t), &extensionsLenPosition); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the encrypted_extensions extension */ ret = PackEncryptedExs(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Close extensions length field */ PackCloseUint16Field(pkt, extensionsLenPosition); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 && HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/pack/src/pack_encrypted_extensions.c
C
unknown
5,100
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdbool.h> #include "hitls_build.h" #include "securec.h" #include "cipher_suite.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_bytes.h" #include "bsl_list.h" #include "hitls_error.h" #include "hitls_sni.h" #include "hitls_cert_type.h" #include "hitls_crypt_type.h" #include "hitls_session.h" #include "tls.h" #include "hs_ctx.h" #include "hs_extensions.h" #include "hs.h" #include "hs_msg.h" #include "hs_common.h" #include "session.h" #include "hs_verify.h" #include "pack_common.h" #include "custom_extensions.h" #include "pack_extensions.h" #include "config_type.h" #define EXTENSION_MSG(exMsgT, needP, packF) \ .exMsgType = (exMsgT), \ .needPack = (needP), \ .packFunc = (packF), \ // Pack the extension header. int32_t PackExtensionHeader(uint16_t exMsgType, uint16_t exMsgLen, PackPacket *pkt) { int32_t ret = PackAppendUint16ToBuf(pkt, exMsgType); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendUint16ToBuf(pkt, exMsgLen); if (ret != HITLS_SUCCESS) { return ret; } ret = PackReserveBytes(pkt, exMsgLen, NULL); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } static int32_t PackExtensions(const TLS_Ctx *ctx, PackPacket *pkt, PackExtInfo *extMsgList, uint32_t listSize) { int32_t ret = HITLS_SUCCESS; for (uint32_t index = 0; index < listSize; index++) { if (extMsgList[index].needPack == false) { continue; } /* Empty expansion */ if (extMsgList[index].packFunc == NULL) { ret = PackEmptyExtension(extMsgList[index].exMsgType, extMsgList[index].needPack, pkt); } else { /* Non-empty expansion */ ret = extMsgList[index].packFunc(ctx, pkt); } if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } static int32_t PackExtensionEnd(PackPacket *pkt, uint32_t extensionLenPosition) { uint32_t extensionLength = 0; int32_t ret = PackGetSubBuffer(pkt, extensionLenPosition, &extensionLength, NULL); if (ret != HITLS_SUCCESS) { return ret; } /* Update the packet length */ if (extensionLength != sizeof(uint16_t)) { PackCloseUint16Field(pkt, extensionLenPosition); } else { *pkt->bufOffset -= sizeof(uint16_t); } return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 static bool IsNeedPreSharedKey(const TLS_Ctx *ctx) { if (ctx->config.tlsConfig.maxVersion != HITLS_VERSION_TLS13) { return false; } if (ctx->hsCtx->state == TRY_SEND_HELLO_RETRY_REQUEST) { /* hello retry request does not contain the psk */ return false; } return true; } bool Tls13NeedPack(const TLS_Ctx *ctx, uint32_t version) { bool tls13NeedPack = false; if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { tls13NeedPack = false; } else { tls13NeedPack = (version >= HITLS_VERSION_TLS13) ? true : false; } return tls13NeedPack; } static int32_t PackCookie(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint32_t exMsgDataLen = 0u; if (ctx->negotiatedInfo.cookie == NULL) { return HITLS_SUCCESS; } /* Calculate the extension length */ exMsgDataLen = sizeof(uint16_t) + (ctx->negotiatedInfo.cookieSize); uint32_t cookieLen = ctx->negotiatedInfo.cookieSize; ret = PackExtensionHeader(HS_EX_TYPE_COOKIE, exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } (void)PackAppendUint16ToBuf(pkt, cookieLen); /* Pack the cookie */ (void)PackAppendDataToBuf(pkt, ctx->negotiatedInfo.cookie, cookieLen); ctx->hsCtx->extFlag.haveCookie = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ static int32_t PackPointFormats(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgHeaderLen = 0u; uint8_t exMsgDataLen = 0u; const TLS_Config *config = &(ctx->config.tlsConfig); if (config->pointFormatsSize == 0) { return HITLS_SUCCESS; } if (config->pointFormats == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15415, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack point formats extension error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } /* Calculate the extension length */ exMsgHeaderLen = sizeof(uint8_t); exMsgDataLen = (uint8_t)config->pointFormatsSize; ret = PackExtensionHeader(HS_EX_TYPE_POINT_FORMATS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the extension point format */ (void)PackAppendUint8ToBuf(pkt, exMsgDataLen); for (uint32_t index = 0; index < config->pointFormatsSize; index++) { (void)PackAppendUint8ToBuf(pkt, config->pointFormats[index]); } /* Set the extension flag */ ctx->hsCtx->extFlag.havePointFormats = true; return HITLS_SUCCESS; } int32_t PackEmptyExtension(uint16_t exMsgType, bool needPack, PackPacket *pkt) { if (needPack) { int32_t ret = PackExtensionHeader(exMsgType, 0u, pkt); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #ifdef HITLS_TLS_HOST_CLIENT #ifdef HITLS_TLS_FEATURE_SNI static int32_t PackServerName(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgDataLen = 0u; uint8_t *hostName = NULL; uint8_t *serverName = NULL; uint32_t hostNameSize, serverNameSize = 0u; const TLS_Config *config = &(ctx->config.tlsConfig); bool isNotTls13 = (config->maxVersion < HITLS_VERSION_TLS13 || config->maxVersion == HITLS_VERSION_DTLS12); (void)isNotTls13; (void)hostNameSize; (void)hostName; #ifdef HITLS_TLS_FEATURE_SESSION /* When a session whose protocol version is earlier than HITLS_VERSION_TLS13 is resumed, the servername extension * field is the hostname in the session */ if (isNotTls13 && ctx->session != NULL) { /* Obtain the hostname in the session */ SESS_GetHostName(ctx->session, &hostNameSize, &hostName); serverName = hostName; } else #endif { /* Obtain the servername in the config */ serverName = config->serverName; } if (serverName == NULL) { return HITLS_SUCCESS; } serverNameSize = (uint32_t)strlen((char *)serverName); /* Calculate the extension length */ /* server Name list Length + server Name Type + Server Name Length + Server Name */ exMsgDataLen = sizeof(uint16_t) + sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint8_t) * serverNameSize; ret = PackExtensionHeader(HS_EX_TYPE_SERVER_NAME, exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the extension Server Name Indication extension */ /* server Name list Length */ (void)PackAppendUint16ToBuf(pkt, exMsgDataLen - sizeof(uint16_t)); /* server Name Type */ (void)PackAppendUint8ToBuf(pkt, HITLS_SNI_HOSTNAME_TYPE); /* Server Name Length */ (void)PackAppendUint16ToBuf(pkt, (uint16_t)serverNameSize); /* Server Name */ (void)PackAppendDataToBuf(pkt, serverName, serverNameSize); /* Set the extension flag */ ctx->hsCtx->extFlag.haveServerName = true; return HITLS_SUCCESS; } static bool IsNeedClientPackServerName(const TLS_Ctx *ctx) { const TLS_Config *config = &(ctx->config.tlsConfig); /* not in session resumption */ if (ctx->session == NULL) { if (config->serverName == NULL) { return false; } } /* The session is being resumed */ if (ctx->session != NULL) { if (config->maxVersion == HITLS_VERSION_TLS13 && config->serverName == NULL) { return false; } } return true; } #endif /* HITLS_TLS_FEATURE_SNI */ static int32_t PackClientSignatureAlgorithms(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgHeaderLen = 0u; uint16_t exMsgDataLen = 0u; const TLS_Config *config = &(ctx->config.tlsConfig); if (config->signAlgorithmsSize == 0) { return HITLS_SUCCESS; } if (config->signAlgorithms == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15413, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack signature algirithms extension error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } uint32_t signAlgorithmsSize = 0; uint16_t *signAlgorithms = CheckSupportSignAlgorithms(ctx, config->signAlgorithms, config->signAlgorithmsSize, &signAlgorithmsSize); if (signAlgorithms == NULL || signAlgorithmsSize == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17309, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "no available signAlgorithms", 0, 0, 0, 0); BSL_SAL_FREE(signAlgorithms); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH; } /* Calculate the extension length */ exMsgHeaderLen = sizeof(uint16_t); exMsgDataLen = sizeof(uint16_t) * (uint16_t)signAlgorithmsSize; /* Pack the extension header */ ret = PackExtensionHeader(HS_EX_TYPE_SIGNATURE_ALGORITHMS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(signAlgorithms); return ret; } /* Pack the extended signature algorithm. */ (void)PackAppendUint16ToBuf(pkt, exMsgDataLen); for (uint32_t index = 0; index < signAlgorithmsSize; index++) { (void)PackAppendUint16ToBuf(pkt, signAlgorithms[index]); } BSL_SAL_FREE(signAlgorithms); /* Set the extension flag */ ctx->hsCtx->extFlag.haveSignatureAlgorithms = true; return HITLS_SUCCESS; } static int32_t PackClientSupportedGroups(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgHeaderLen = 0u; uint16_t exMsgDataLen = 0u; const TLS_Config *config = &(ctx->config.tlsConfig); if (config->groupsSize == 0) { return HITLS_SUCCESS; } if (config->groups == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15414, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack supported groups extension error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } /* Calculate the extension length */ exMsgHeaderLen = sizeof(uint16_t); exMsgDataLen = sizeof(uint16_t) * (uint16_t)config->groupsSize; ret = PackExtensionHeader(HS_EX_TYPE_SUPPORTED_GROUPS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack extended supported groups */ (void)PackAppendUint16ToBuf(pkt, exMsgDataLen); for (uint32_t index = 0; index < config->groupsSize; index++) { (void)PackAppendUint16ToBuf(pkt, config->groups[index]); } /* Set the extension flag */ ctx->hsCtx->extFlag.haveSupportedGroups = true; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_ALPN static int32_t PackClientAlpnList(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgHeaderLen = 0u; uint8_t exMsgDataLen = 0u; const TLS_Config *config = &(ctx->config.tlsConfig); if (config->alpnListSize == 0) { return HITLS_SUCCESS; } if (config->alpnList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15416, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack alpn list extension error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } /* Calculate the extension length */ exMsgHeaderLen = sizeof(uint16_t); exMsgDataLen = (uint8_t)config->alpnListSize; ret = PackExtensionHeader(HS_EX_TYPE_APP_LAYER_PROTOCOLS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } (void)PackAppendUint16ToBuf(pkt, exMsgDataLen); (void)PackAppendDataToBuf(pkt, config->alpnList, config->alpnListSize); /* Set the extension flag */ ctx->hsCtx->extFlag.haveAlpn = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET static int32_t PackClientTicket(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint8_t *ticket = NULL; uint32_t ticketSize = 0; uint16_t sessVersion = HITLS_VERSION_TLS13; if (ctx->session != NULL) { HITLS_SESS_GetProtocolVersion(ctx->session, &sessVersion); } /* Whether the ticket belongs to tls1.3 needs to be determined */ if (sessVersion != HITLS_VERSION_TLS13) { SESS_GetTicket(ctx->session, &ticket, &ticketSize); } ret = PackExtensionHeader(HS_EX_TYPE_SESSION_TICKET, (uint16_t)ticketSize, pkt); if (ret != HITLS_SUCCESS) { return ret; } (void)PackAppendDataToBuf(pkt, ticket, ticketSize); /* Set the extension flag. */ ctx->hsCtx->extFlag.haveTicket = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_RENEGOTIATION static int32_t PackClientSecRenegoInfo(const TLS_Ctx *ctx, PackPacket *pkt) { if (!ctx->negotiatedInfo.isRenegotiation) { return HITLS_SUCCESS; } /* Calculate the extension length */ const uint8_t *clientData = ctx->negotiatedInfo.clientVerifyData; uint32_t clientDataSize = ctx->negotiatedInfo.clientVerifyDataSize; uint16_t exMsgHeaderLen = sizeof(uint8_t); uint16_t exMsgDataLen = (uint16_t)clientDataSize; /* Pack the extension header */ int32_t ret; ret = PackExtensionHeader(HS_EX_TYPE_RENEGOTIATION_INFO, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the length of secRenegoInfo */ (void)PackAppendUint8ToBuf(pkt, (uint8_t)clientDataSize); /* Pack the secRenegoInfo content */ (void)PackAppendDataToBuf(pkt, clientData, clientDataSize); return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ static bool IsNeedPackEcExtension(const TLS_Ctx *ctx) { const TLS_Config *config = &(ctx->config.tlsConfig); #ifdef HITLS_TLS_PROTO_TLS13 if ((config->maxVersion == HITLS_VERSION_TLS13)) { uint32_t needKeyShareMode = TLS13_KE_MODE_PSK_WITH_DHE | TLS13_CERT_AUTH_WITH_DHE; if ((ctx->negotiatedInfo.tls13BasicKeyExMode & needKeyShareMode) != 0) { return true; } } #endif /* HITLS_TLS_PROTO_TLS13 */ for (uint32_t index = 0; index < config->cipherSuitesSize; index++) { CipherSuiteInfo cipherInfo = {0}; /* The returned value does not need to be checked. The validity of the cipher suite is checked when the cipher * suite is configured */ (void)CFG_GetCipherSuiteInfo(config->cipherSuites[index], &cipherInfo); /* The ECC algorithm suite exists */ if ((cipherInfo.authAlg == HITLS_AUTH_ECDSA) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_ECDHE) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_ECDH) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_ECDHE_PSK)) { return true; } } return false; } #ifdef HITLS_TLS_PROTO_TLS13 static int32_t PackClientSupportedVersions(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgHeaderLen = 0u; uint8_t exMsgDataLen = 0u; const TLS_Config *config = &(ctx->config.tlsConfig); uint16_t minVersion = config->minVersion; uint16_t maxVersion = config->maxVersion; if (config->minVersion < HITLS_VERSION_SSL30 || config->maxVersion > HITLS_VERSION_TLS13) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15418, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack supported version extension error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } /* Calculate the extension length */ exMsgHeaderLen = sizeof(uint8_t); exMsgDataLen = sizeof(uint16_t) * (maxVersion - minVersion + 1); ret = PackExtensionHeader(HS_EX_TYPE_SUPPORTED_VERSIONS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the TLS version supported by the extension */ (void)PackAppendUint8ToBuf(pkt, exMsgDataLen); for (uint16_t version = maxVersion; version >= minVersion; version--) { (void)PackAppendUint16ToBuf(pkt, version); } /* Set the extension flag */ ctx->hsCtx->extFlag.haveSupportedVers = true; return HITLS_SUCCESS; } static int32_t PackClientPskKeyExModes(const TLS_Ctx *ctx, PackPacket *pkt) { bool allowOnly = false; bool allowDhe = false; const uint32_t configKxMode = ctx->config.tlsConfig.keyExchMode; uint16_t exMsgHeaderLen = sizeof(uint8_t); uint16_t exMsgDataLen = 0; if ((bool)(configKxMode & TLS13_KE_MODE_PSK_WITH_DHE)) { exMsgDataLen++; allowDhe = true; } if ((bool)(configKxMode & TLS13_KE_MODE_PSK_ONLY)) { exMsgDataLen++; allowOnly = true; } int32_t ret = PackExtensionHeader(HS_EX_TYPE_PSK_KEY_EXCHANGE_MODES, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the length of the key exchange pattern extension */ (void)PackAppendUint8ToBuf(pkt, (uint8_t)exMsgDataLen); if (allowDhe) { (void)PackAppendUint8ToBuf(pkt, PSK_DHE_KE); } if (allowOnly) { (void)PackAppendUint8ToBuf(pkt, PSK_KE); } ctx->hsCtx->extFlag.havePskExMode = true; return HITLS_SUCCESS; } static int32_t PackClientKeyShare(const TLS_Ctx *ctx, PackPacket *pkt) { uint32_t needKeyShareMode = TLS13_KE_MODE_PSK_WITH_DHE | TLS13_CERT_AUTH_WITH_DHE; if ((ctx->negotiatedInfo.tls13BasicKeyExMode & needKeyShareMode) == 0) { return HITLS_SUCCESS; } KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; if (kxCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16939, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "kxCtx is null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } uint16_t keyShareLen = 0; KeyShareParam *keyShare = &(kxCtx->keyExchParam.share); uint32_t secondPubKeyLen = 0u; uint32_t pubKeyLen = SAL_CRYPT_GetCryptLength(ctx, HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN, keyShare->group); if (pubKeyLen == 0u) { BSL_ERR_PUSH_ERROR(HITLS_PACK_INVALID_KX_PUBKEY_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15422, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid keyShare length.", 0, 0, 0, 0); return HITLS_PACK_INVALID_KX_PUBKEY_LENGTH; } keyShareLen += sizeof(uint16_t) + sizeof(uint16_t) + pubKeyLen; if (keyShare->secondGroup != HITLS_NAMED_GROUP_BUTT) { secondPubKeyLen = SAL_CRYPT_GetCryptLength(ctx, HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN, keyShare->secondGroup); if (secondPubKeyLen == 0u) { BSL_ERR_PUSH_ERROR(HITLS_PACK_INVALID_KX_PUBKEY_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15422, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid keyShare length.", 0, 0, 0, 0); return HITLS_PACK_INVALID_KX_PUBKEY_LENGTH; } keyShareLen += sizeof(uint16_t) + sizeof(uint16_t) + secondPubKeyLen; } int32_t ret = PackExtensionHeader(HS_EX_TYPE_KEY_SHARE, sizeof(uint16_t) + keyShareLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the total length of client_keyShare */ (void)PackAppendUint16ToBuf(pkt, keyShareLen); /* Pack a group */ (void)PackAppendUint16ToBuf(pkt, (uint16_t)keyShare->group); /* Length of the Pack KeyExChange */ (void)PackAppendUint16ToBuf(pkt, (uint16_t)pubKeyLen); uint32_t pubKeyUsedLen = 0; uint8_t *pubKeyBuf = NULL; (void)PackReserveBytes(pkt, pubKeyLen, &pubKeyBuf); /* Pack KeyExChange */ ret = SAL_CRYPT_EncodeEcdhPubKey(kxCtx->key, pubKeyBuf, pubKeyLen, &pubKeyUsedLen); if (ret != HITLS_SUCCESS || pubKeyUsedLen != pubKeyLen) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15423, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode client keyShare key fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } (void)PackSkipBytes(pkt, pubKeyUsedLen); if (keyShare->secondGroup != HITLS_NAMED_GROUP_BUTT) { (void)PackAppendUint16ToBuf(pkt, (uint16_t)keyShare->secondGroup); (void)PackAppendUint16ToBuf(pkt, (uint16_t)secondPubKeyLen); uint8_t *secondPubKeyBuf = NULL; (void)PackReserveBytes(pkt, secondPubKeyLen, &secondPubKeyBuf); ret = SAL_CRYPT_EncodeEcdhPubKey(kxCtx->secondKey, secondPubKeyBuf, secondPubKeyLen, &pubKeyUsedLen); if (ret != HITLS_SUCCESS || pubKeyUsedLen != secondPubKeyLen) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15423, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode client keyShare key fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } (void)PackSkipBytes(pkt, pubKeyUsedLen); } ctx->hsCtx->extFlag.haveKeyShare = true; return HITLS_SUCCESS; } static uint32_t GetPreSharedKeyExtLen(const PskInfo13 *pskInfo) { uint32_t extLen = HS_EX_HEADER_LEN; uint32_t binderLen = 0; if (pskInfo->resumeSession != NULL) { HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT; binderLen = HS_GetBinderLen(pskInfo->resumeSession, &hashAlg); if (binderLen == 0) { return 0; } uint8_t *ticket = NULL; uint32_t ticketSize = 0; SESS_GetTicket(pskInfo->resumeSession, &ticket, &ticketSize); extLen += sizeof(uint16_t) + ticketSize + sizeof(uint32_t) + sizeof(uint8_t) + binderLen; } if (pskInfo->userPskSess != NULL) { HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT; binderLen = HS_GetBinderLen(pskInfo->userPskSess->pskSession, &hashAlg); if (binderLen == 0) { return 0; } extLen += sizeof(uint16_t) + pskInfo->userPskSess->identityLen + sizeof(uint32_t) + sizeof(uint8_t) + binderLen; } extLen += sizeof(uint16_t) + sizeof(uint16_t); return extLen; } static void PackClientPreSharedKeyIdentity(const TLS_Ctx *ctx, uint8_t *buf, uint32_t bufLen) { PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; uint32_t offset = 0; uint32_t offsetStamp = offset; offset += sizeof(uint16_t); // skip identities len if (pskInfo->resumeSession != NULL) { uint8_t *ticket = NULL; uint32_t ticketSize = 0; SESS_GetTicket(pskInfo->resumeSession, &ticket, &ticketSize); BSL_Uint16ToByte((uint16_t)ticketSize, &buf[offset]); offset += sizeof(uint16_t); // has passed the verification above, and it must be successful here. (void)memcpy_s(&buf[offset], bufLen - offset, ticket, ticketSize); offset += ticketSize; uint32_t ageSec = (uint32_t)((uint64_t)BSL_SAL_CurrentSysTimeGet() - SESS_GetStartTime(pskInfo->resumeSession)); uint32_t agemSec = ageSec * 1000 + (uint32_t)SESS_GetTicketAgeAdd(pskInfo->resumeSession); /* unit: ms */ BSL_Uint32ToByte(agemSec, &buf[offset]); offset += sizeof(uint32_t); } if (pskInfo->userPskSess != NULL) { BSL_Uint16ToByte((uint16_t)pskInfo->userPskSess->identityLen, &buf[offset]); offset += sizeof(uint16_t); (void)memcpy_s(&buf[offset], bufLen - offset, // has passed the verification above, and it must be successful here pskInfo->userPskSess->identity, pskInfo->userPskSess->identityLen); offset += pskInfo->userPskSess->identityLen; BSL_Uint32ToByte(0, &buf[offset]); offset += sizeof(uint32_t); } BSL_Uint16ToByte((uint16_t)(offset - offsetStamp - sizeof(uint16_t)), &buf[offsetStamp]); } // ClientPreSharedKey: pskid, binder, see rfc 8446 section 4.2.11, currently support one pskid and one binder static int32_t PackClientPreSharedKey(const TLS_Ctx *ctx, PackPacket *pkt) { PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; if (pskInfo->resumeSession == NULL && pskInfo->userPskSess == NULL) { return HITLS_SUCCESS; } uint32_t minLen = GetPreSharedKeyExtLen(pskInfo); if (minLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_PACK_PRE_SHARED_KEY_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15939, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Binder size is zero when PackClientPreSharedKey", 0, 0, 0, 0); return HITLS_PACK_PRE_SHARED_KEY_ERR; } int32_t ret = PackExtensionHeader(HS_EX_TYPE_PRE_SHARED_KEY, (uint16_t)(minLen - HS_EX_HEADER_LEN), pkt); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *pskBuf = NULL; ret = PackReserveBytes(pkt, minLen - HS_EX_HEADER_LEN, &pskBuf); if (ret != HITLS_SUCCESS) { return ret; } ret = PackSkipBytes(pkt, minLen - HS_EX_HEADER_LEN); if (ret != HITLS_SUCCESS) { return ret; } PackClientPreSharedKeyIdentity(ctx, pskBuf, minLen - HS_EX_HEADER_LEN); // pack binder after fills in the packet header and extension length. call PackClientPreSharedKeyBinders ctx->hsCtx->extFlag.havePreShareKey = true; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES int32_t PackClientCAList(const TLS_Ctx *ctx, PackPacket *pkt) { const TLS_Config *config = &(ctx->config.tlsConfig); int32_t ret = PackAppendUint16ToBuf(pkt, HS_EX_TYPE_CERTIFICATE_AUTHORITIES); if (ret != HITLS_SUCCESS) { return ret; } uint32_t extensionLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint16_t), &extensionLenPosition); if (ret != HITLS_SUCCESS) { return ret; } uint32_t caLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint16_t), &caLenPosition); if (ret != HITLS_SUCCESS) { return ret; } ret = PackTrustedCAList(config->caList, pkt); if (ret != HITLS_SUCCESS) { return ret; } PackCloseUint16Field(pkt, caLenPosition); PackCloseUint16Field(pkt, extensionLenPosition); return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ #ifdef HITLS_TLS_FEATURE_PHA static bool IsNeedPackPha(const TLS_Ctx *ctx) { const TLS_Config *tlsConfig = &ctx->config.tlsConfig; if (tlsConfig->maxVersion != HITLS_VERSION_TLS13) { return false; } return tlsConfig->isSupportPostHandshakeAuth; } #endif /* HITLS_TLS_FEATURE_PHA */ #endif /* HITLS_TLS_PROTO_TLS13 */ static bool IsNeedEms(const TLS_Ctx *ctx) { if (ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLCP_DTLCP11) { return false; } return true; } // Pack the non-null extension of client hello. static int32_t PackClientExtensions(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; const TLS_Config *tlsConfig = &ctx->config.tlsConfig; (void)tlsConfig; #ifdef HITLS_TLS_FEATURE_RENEGOTIATION const TLS_NegotiatedInfo *negoInfo = &ctx->negotiatedInfo; #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ #ifdef HITLS_TLS_PROTO_TLS13 bool isTls13 = (tlsConfig->maxVersion == HITLS_VERSION_TLS13); #endif /* HITLS_TLS_PROTO_TLS13 */ /* Check whether EC extensions need to be filled */ bool isEcNeed = IsNeedPackEcExtension(ctx); /* If the version is earlier than tls1.2, the signature extension cannot be sent */ bool isSignAlgNeed = (ctx->config.tlsConfig.maxVersion >= HITLS_VERSION_TLS12); #ifdef HITLS_TLS_FEATURE_SESSION_TICKET /* Do not send the sessionticket in the PTO scenario */ bool isSessionTicketNeed = IsTicketSupport(ctx); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_PHA bool isNeedPha = IsNeedPackPha(ctx); #endif /* HITLS_TLS_FEATURE_PHA */ PackExtInfo extMsgList[] = { #ifdef HITLS_TLS_FEATURE_SNI { EXTENSION_MSG(HS_EX_TYPE_SERVER_NAME, IsNeedClientPackServerName(ctx), PackServerName) }, #endif /* HITLS_TLS_FEATURE_SNI */ { EXTENSION_MSG(HS_EX_TYPE_SIGNATURE_ALGORITHMS, isSignAlgNeed, PackClientSignatureAlgorithms) }, { EXTENSION_MSG(HS_EX_TYPE_SUPPORTED_GROUPS, isEcNeed, PackClientSupportedGroups) }, { EXTENSION_MSG(HS_EX_TYPE_POINT_FORMATS, isEcNeed, PackPointFormats) }, #ifdef HITLS_TLS_PROTO_TLS13 { EXTENSION_MSG(HS_EX_TYPE_SUPPORTED_VERSIONS, isTls13, PackClientSupportedVersions) }, #endif /* HITLS_TLS_PROTO_TLS13 */ { EXTENSION_MSG(HS_EX_TYPE_EARLY_DATA, false, NULL) }, #ifdef HITLS_TLS_PROTO_TLS13 { EXTENSION_MSG(HS_EX_TYPE_COOKIE, isTls13, PackCookie) }, #ifdef HITLS_TLS_FEATURE_PHA { EXTENSION_MSG(HS_EX_TYPE_POST_HS_AUTH, isNeedPha, NULL) }, #endif /* HITLS_TLS_FEATURE_PHA */ #endif /* HITLS_TLS_PROTO_TLS13 */ { EXTENSION_MSG(HS_EX_TYPE_EXTENDED_MASTER_SECRET, IsNeedEms(ctx), NULL) }, #ifdef HITLS_TLS_FEATURE_ALPN { EXTENSION_MSG(HS_EX_TYPE_APP_LAYER_PROTOCOLS, (tlsConfig->alpnList != NULL && ctx->state == CM_STATE_HANDSHAKING), PackClientAlpnList) }, #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_PROTO_TLS13 { EXTENSION_MSG(HS_EX_TYPE_PSK_KEY_EXCHANGE_MODES, isTls13, PackClientPskKeyExModes) }, { EXTENSION_MSG(HS_EX_TYPE_KEY_SHARE, isTls13, PackClientKeyShare) }, #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES { EXTENSION_MSG(HS_EX_TYPE_CERTIFICATE_AUTHORITIES, isTls13 && tlsConfig->caList != NULL, PackClientCAList) }, #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_FEATURE_RENEGOTIATION { EXTENSION_MSG(HS_EX_TYPE_RENEGOTIATION_INFO, negoInfo->isSecureRenegotiation, PackClientSecRenegoInfo) }, #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET { EXTENSION_MSG(HS_EX_TYPE_SESSION_TICKET, isSessionTicketNeed, PackClientTicket) }, #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_ETM { EXTENSION_MSG(HS_EX_TYPE_ENCRYPT_THEN_MAC, tlsConfig->isEncryptThenMac, NULL) }, #endif /* HITLS_TLS_FEATURE_ETM */ #ifdef HITLS_TLS_PROTO_TLS13 { EXTENSION_MSG(HS_EX_TYPE_PRE_SHARED_KEY, IsNeedPreSharedKey(ctx), PackClientPreSharedKey) }, #endif /* HITLS_TLS_PROTO_TLS13 */ }; #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsPackNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), HITLS_EX_TYPE_CLIENT_HELLO)) { ret = PackCustomExtensions(ctx, pkt, HITLS_EX_TYPE_CLIENT_HELLO, NULL, 0); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ ret = PackExtensions(ctx, pkt, extMsgList, sizeof(extMsgList) / sizeof(extMsgList[0])); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_PHA ctx->hsCtx->extFlag.havePostHsAuth = isNeedPha; #endif /* HITLS_TLS_FEATURE_PHA */ ctx->hsCtx->extFlag.haveExtendedMasterSecret = IsNeedEms(ctx); #ifdef HITLS_TLS_FEATURE_ETM ctx->hsCtx->extFlag.haveEncryptThenMac = ctx->config.tlsConfig.isEncryptThenMac; #endif /* HITLS_TLS_FEATURE_ETM */ return HITLS_SUCCESS; } // Pack the Client Hello extension int32_t PackClientExtension(const TLS_Ctx *ctx, PackPacket *pkt) { uint32_t extensionLenPosition = 0u; int32_t ret = PackStartLengthField(pkt, sizeof(uint16_t), &extensionLenPosition); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the client hello extension content */ ret = PackClientExtensions(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } return PackExtensionEnd(pkt, extensionLenPosition); } #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER static bool IsServerNeedPackEcExtension(const TLS_Ctx *ctx) { const TLS_NegotiatedInfo *negotiatedInfo = &(ctx->negotiatedInfo); CipherSuiteInfo cipherInfo = negotiatedInfo->cipherSuiteInfo; /* The negotiated algorithm suite is the ECC cipher suite */ if (((cipherInfo.authAlg == HITLS_AUTH_ECDSA) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_ECDHE) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_ECDH) || (cipherInfo.kxAlg == HITLS_KEY_EXCH_ECDHE_PSK)) && ctx->haveClientPointFormats == true) { return true; } return false; } #ifdef HITLS_TLS_FEATURE_ALPN int32_t PackServerSelectAlpnProto(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgHeaderLen = 0u; uint8_t exMsgDataLen = 0u; if (ctx->negotiatedInfo.alpnSelectedSize == 0) { return HITLS_SUCCESS; } /* Calculate the extension length */ exMsgHeaderLen = sizeof(uint16_t); exMsgDataLen = (uint8_t)ctx->negotiatedInfo.alpnSelectedSize + sizeof(uint8_t); /* Pack the extension header */ ret = PackExtensionHeader(HS_EX_TYPE_APP_LAYER_PROTOCOLS, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } (void)PackAppendUint16ToBuf(pkt, (uint16_t)exMsgDataLen); (void)PackAppendUint8ToBuf(pkt, exMsgDataLen - sizeof(uint8_t)); (void)PackAppendDataToBuf(pkt, ctx->negotiatedInfo.alpnSelected, ctx->negotiatedInfo.alpnSelectedSize); /* Set the extension flag */ ctx->hsCtx->extFlag.haveAlpn = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t PackHrrKeyShare(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgDataLen = 0u; KeyShareParam *keyShare = &(ctx->hsCtx->kxCtx->keyExchParam.share); /* Message length = group length */ exMsgDataLen = sizeof(uint16_t); ret = PackExtensionHeader(HS_EX_TYPE_KEY_SHARE, exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } /* Pack a group */ (void)PackAppendUint16ToBuf(pkt, (uint16_t)keyShare->group); ctx->hsCtx->extFlag.haveKeyShare = true; return HITLS_SUCCESS; } static int32_t PackServerKeyShare(const TLS_Ctx *ctx, PackPacket *pkt) { KeyShareParam *keyShare = &(ctx->hsCtx->kxCtx->keyExchParam.share); KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; /* If the peer public key does not exist, the psk_only mode is used. In this case, the key share does not need to be * sent */ if (kxCtx->peerPubkey == NULL) { return HITLS_SUCCESS; } const TLS_GroupInfo *groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, ctx->negotiatedInfo.negotiatedGroup); if (groupInfo == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16246, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "group info not found", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } uint32_t pubKeyLen = groupInfo->isKem ? groupInfo->ciphertextLen : groupInfo->pubkeyLen; if (pubKeyLen == 0u || (groupInfo->isKem && pubKeyLen != kxCtx->ciphertextLen)) { BSL_ERR_PUSH_ERROR(HITLS_PACK_INVALID_KX_PUBKEY_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15428, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid keyShare length.", 0, 0, 0, 0); return HITLS_PACK_INVALID_KX_PUBKEY_LENGTH; } /* Length of group + Length of KeyExChange + KeyExChange */ uint16_t exMsgDataLen = sizeof(uint16_t) + sizeof(uint16_t) + (uint16_t)pubKeyLen; int32_t ret = PackReserveBytes(pkt, exMsgDataLen + HS_EX_HEADER_LEN, NULL); if (ret != HITLS_SUCCESS) { return ret; } (void)PackExtensionHeader(HS_EX_TYPE_KEY_SHARE, exMsgDataLen, pkt); /* Pack a group */ (void)PackAppendUint16ToBuf(pkt, (uint16_t)keyShare->group); /* Length of the paced KeyExChange */ (void)PackAppendUint16ToBuf(pkt, (uint16_t)pubKeyLen); if (groupInfo->isKem) { ret = PackAppendDataToBuf(pkt, kxCtx->ciphertext, kxCtx->ciphertextLen); if (ret != HITLS_SUCCESS) { return ret; } } else { uint8_t *pubKeyBuf = NULL; uint32_t pubKeyUsedLen = 0; (void)PackReserveBytes(pkt, pubKeyLen, &pubKeyBuf); ret = SAL_CRYPT_EncodeEcdhPubKey(kxCtx->key, pubKeyBuf, pubKeyLen, &pubKeyUsedLen); if (ret != HITLS_SUCCESS || pubKeyLen != pubKeyUsedLen) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15429, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode server keyShare key fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } (void)PackSkipBytes(pkt, pubKeyUsedLen); } ctx->hsCtx->extFlag.haveKeyShare = true; return HITLS_SUCCESS; } static int32_t PackServerSupportedVersion(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t exMsgDataLen = 0u; const uint16_t supportedVersion = ctx->negotiatedInfo.version; if (supportedVersion <= 0) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15430, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack supported version extension error, invalid input parameter.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } /* Calculate the extension length */ exMsgDataLen = sizeof(uint16_t); ret = PackExtensionHeader(HS_EX_TYPE_SUPPORTED_VERSIONS, exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } (void)PackAppendUint16ToBuf(pkt, supportedVersion); ctx->hsCtx->extFlag.haveSupportedVers = true; return HITLS_SUCCESS; } static int32_t IsHrrKeyShare(const TLS_Ctx *ctx) { bool haveHrr = ctx->hsCtx->haveHrr; /* Sent or in the process of sending hrr */ bool haveKeyShare = ctx->hsCtx->extFlag.haveKeyShare; /* has packed the keyshare */ if (haveHrr && !haveKeyShare) { return true; } return false; } static int32_t PackServerPreSharedKey(const TLS_Ctx *ctx, PackPacket *pkt) { const PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; if (pskInfo->psk == NULL) { return HITLS_SUCCESS; } int32_t ret = PackExtensionHeader(HS_EX_TYPE_PRE_SHARED_KEY, sizeof(uint16_t), pkt); if (ret != HITLS_SUCCESS) { return ret; } (void)PackAppendUint16ToBuf(pkt, (uint16_t)pskInfo->selectIndex); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t PackServerSecRenegoInfo(const TLS_Ctx *ctx, PackPacket *pkt) { bool isRenegotiation = ctx->negotiatedInfo.isRenegotiation; const uint8_t *clientData = ctx->negotiatedInfo.clientVerifyData; uint32_t clientDataSize = ctx->negotiatedInfo.clientVerifyDataSize; const uint8_t *serverData = ctx->negotiatedInfo.serverVerifyData; uint32_t serverDataSize = ctx->negotiatedInfo.serverVerifyDataSize; /* Calculate the extension length */ uint16_t exMsgHeaderLen = sizeof(uint8_t); /* For renegotiation, the verify data (client data + server data) must be assembled */ uint16_t exMsgDataLen = (uint16_t)(isRenegotiation ? (clientDataSize + serverDataSize) : 0); int32_t ret = PackExtensionHeader(HS_EX_TYPE_RENEGOTIATION_INFO, exMsgHeaderLen + exMsgDataLen, pkt); if (ret != HITLS_SUCCESS) { return ret; } if (!isRenegotiation) { (void)PackAppendUint8ToBuf(pkt, 0); return HITLS_SUCCESS; } /* Pack the length of secRenegoInfo */ (void)PackAppendUint8ToBuf(pkt, (uint8_t)(clientDataSize + serverDataSize)); /* Pack the secRenegoInfo content */ (void)PackAppendDataToBuf(pkt, clientData, clientDataSize); (void)PackAppendDataToBuf(pkt, serverData, serverDataSize); return HITLS_SUCCESS; } #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SNI static bool IsNeedServerPackServerName(const TLS_Ctx *ctx) { const TLS_Config *config = &(ctx->config.tlsConfig); const TLS_NegotiatedInfo *negoInfo = &ctx->negotiatedInfo; /* The protocol version is earlier than tls1.3 and the server accepts the server name. The server hello message sent * by the server contains an empty server name extension */ if (negoInfo->isSniStateOK && (config->maxVersion < HITLS_VERSION_TLS13 || config->maxVersion == HITLS_VERSION_DTLS12)) { return true; } return false; } #endif /* HITLS_TLS_FEATURE_SNI */ #ifdef HITLS_TLS_FEATURE_ETM static bool IsNeedServerPackEncryptThenMac(const TLS_Ctx *ctx) { const TLS_Config *config = &(ctx->config.tlsConfig); const TLS_NegotiatedInfo *negoInfo = &ctx->negotiatedInfo; if (config->isEncryptThenMac && negoInfo->isEncryptThenMac) { return true; } return false; } #endif /* HITLS_TLS_FEATURE_ETM */ // Pack the empty extension of Server Hello static int32_t PackServerExtensions(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_PROTO_TLS13 uint32_t version = HS_GetVersion(ctx); bool isHrrKeyshare = IsHrrKeyShare(ctx); bool isTls13 = Tls13NeedPack(ctx, version); #endif /* HITLS_TLS_PROTO_TLS13 */ const TLS_NegotiatedInfo *negoInfo = &ctx->negotiatedInfo; (void)negoInfo; PackExtInfo extMsgList[] = { #ifdef HITLS_TLS_FEATURE_SNI { EXTENSION_MSG(HS_EX_TYPE_SERVER_NAME, IsNeedServerPackServerName(ctx), NULL) }, #endif /* HITLS_TLS_FEATURE_SNI */ #ifdef HITLS_TLS_PROTO_TLS13 { EXTENSION_MSG(HS_EX_TYPE_COOKIE, isTls13, PackCookie) }, #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET { EXTENSION_MSG(HS_EX_TYPE_SESSION_TICKET, negoInfo->isTicket, NULL) }, #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ { EXTENSION_MSG(HS_EX_TYPE_POINT_FORMATS, IsServerNeedPackEcExtension(ctx), PackPointFormats) }, #ifdef HITLS_TLS_PROTO_TLS13 { EXTENSION_MSG(HS_EX_TYPE_SUPPORTED_VERSIONS, isTls13, PackServerSupportedVersion) }, #endif /* HITLS_TLS_PROTO_TLS13 */ { EXTENSION_MSG(HS_EX_TYPE_EXTENDED_MASTER_SECRET, negoInfo->isExtendedMasterSecret, NULL) }, #ifdef HITLS_TLS_FEATURE_ALPN { .exMsgType = HS_EX_TYPE_APP_LAYER_PROTOCOLS, .needPack = (negoInfo->alpnSelected != NULL #ifdef HITLS_TLS_PROTO_TLS13 && !isTls13 #endif ), .packFunc = PackServerSelectAlpnProto }, #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_PROTO_TLS13 { EXTENSION_MSG(HS_EX_TYPE_KEY_SHARE, (isTls13 && !isHrrKeyshare), PackServerKeyShare) }, { EXTENSION_MSG(HS_EX_TYPE_KEY_SHARE, (isTls13 && isHrrKeyshare), PackHrrKeyShare) }, #endif /* HITLS_TLS_PROTO_TLS13 */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) { EXTENSION_MSG(HS_EX_TYPE_RENEGOTIATION_INFO, negoInfo->isSecureRenegotiation, PackServerSecRenegoInfo) }, #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_ETM { EXTENSION_MSG(HS_EX_TYPE_ENCRYPT_THEN_MAC, IsNeedServerPackEncryptThenMac(ctx), NULL) }, #endif /* HITLS_TLS_FEATURE_ETM */ #ifdef HITLS_TLS_PROTO_TLS13 /* The preshare key must be the last extension */ { EXTENSION_MSG(HS_EX_TYPE_PRE_SHARED_KEY, IsNeedPreSharedKey(ctx), PackServerPreSharedKey) }, #endif /* HITLS_TLS_PROTO_TLS13 */ }; #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION uint32_t context = 0; #ifdef HITLS_TLS_PROTO_TLS13 if (isTls13) { if (isHrrKeyshare) { context = HITLS_EX_TYPE_HELLO_RETRY_REQUEST; } else { context = HITLS_EX_TYPE_TLS1_3_SERVER_HELLO; } } else #endif { context = HITLS_EX_TYPE_TLS1_2_SERVER_HELLO; } if (IsPackNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), context)) { ret = PackCustomExtensions(ctx, pkt, context, NULL, 0); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ ret = PackExtensions(ctx, pkt, extMsgList, sizeof(extMsgList) / sizeof(extMsgList[0])); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } // Pack the Server Hello extension int32_t PackServerExtension(const TLS_Ctx *ctx, PackPacket *pkt) { /* Obtain the packet header length */ uint32_t extensionLenPosition = 0u; int32_t ret = PackStartLengthField(pkt, sizeof(uint16_t), &extensionLenPosition); if (ret != HITLS_SUCCESS) { return ret; } /* Pack the server hello extension content */ ret = PackServerExtensions(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } return PackExtensionEnd(pkt, extensionLenPosition); } #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/pack/src/pack_extensions.c
C
unknown
45,587
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 PACK_EXTENSIONS_H #define PACK_EXTENSIONS_H #include <stdint.h> #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * Hook function for packing extensions of client and server. */ typedef int32_t (*PACK_EXT_FUNC)(const TLS_Ctx *ctx, PackPacket *pkt); /** * PackExtInfo structure, used to transfer extension information of ClientHello messages */ typedef struct { uint16_t exMsgType; /**< Extension type of message*/ bool needPack; /**< Whether packing is needed */ PACK_EXT_FUNC packFunc; /**< Hook for packing extensions*/ } PackExtInfo; typedef void (*GET_EXTSIZE_FUNC)(const TLS_Ctx *ctx, uint32_t *exSize); typedef struct { bool needCheck; GET_EXTSIZE_FUNC getSizeFunc; } GetExtFieldSize; /** * @brief Pack Client Hello extension * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH The message buffer length is insufficient */ int32_t PackClientExtension(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack Server Hello extension * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH The message buffer length is insufficient */ int32_t PackServerExtension(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack an empty extension * * @param exMsgType [IN] Extension type * @param needPack [IN] Whether packing is needed * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval HITLS_PACK_NOT_ENOUGH_BUF_LENGTH The message buffer length is insufficient */ int32_t PackEmptyExtension(uint16_t exMsgType, bool needPack, PackPacket *pkt); /** * @brief Pack the header of an extension * * @param exMsgType [IN] Extension type * @param exMsgLen [IN] Extension length * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackExtensionHeader(uint16_t exMsgType, uint16_t exMsgLen, PackPacket *pkt); int32_t PackServerSelectAlpnProto(const TLS_Ctx *ctx, PackPacket *pkt); int32_t PackClientCAList(const TLS_Ctx *ctx, PackPacket *pkt); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end PACK_EXTENSIONS_H */
2301_79861745/bench_create
tls/handshake/pack/src/pack_extensions.h
C
unknown
2,898
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include "hitls_build.h" #include "securec.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 "tls.h" #include "pack_common.h" #include "hs_ctx.h" // pack the Finished message. int32_t PackFinished(const TLS_Ctx *ctx, PackPacket *pkt) { const HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; return PackAppendDataToBuf(pkt, hsCtx->verifyCtx->verifyData, hsCtx->verifyCtx->verifyDataSize); }
2301_79861745/bench_create
tls/handshake/pack/src/pack_finished.c
C
unknown
1,074
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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) && defined(HITLS_TLS_HOST_SERVER) #include <stdint.h> #include "securec.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_security.h" #include "tls.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "hs_ctx.h" #include "pack_common.h" #include "pack_extensions.h" // Pack the HelloVerifyRequest message. int32_t PackHelloVerifyRequest(const TLS_Ctx *ctx, PackPacket *pkt) { const TLS_NegotiatedInfo *negotiatedInfo = &ctx->negotiatedInfo; /* According to rfc6347 4.2.1, message with the cookie length of 0 can be sent, but it is meaningless and will be trapped in an infinite loop. Therefore, cannot sent cookies with the length of 0 here. */ if (negotiatedInfo->cookieSize == 0) { BSL_ERR_PUSH_ERROR(HITLS_PACK_COOKIE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15828, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cookieSize is 0.", 0, 0, 0, 0); return HITLS_PACK_COOKIE_ERR; } uint16_t version = HITLS_VERSION_DTLS10; if (IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask)) { version = HITLS_VERSION_TLCP_DTLCP11; } int32_t ret = PackReserveBytes(pkt, sizeof(uint16_t) + sizeof(uint8_t) + negotiatedInfo->cookieSize, NULL); if (ret != HITLS_SUCCESS) { return ret; } (void)PackAppendUint16ToBuf(pkt, version); (void)PackAppendUint8ToBuf(pkt, (uint8_t)negotiatedInfo->cookieSize); (void)PackAppendDataToBuf(pkt, negotiatedInfo->cookie, negotiatedInfo->cookieSize); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP && HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/pack/src/pack_hello_verify_request.c
C
unknown
2,382
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_KEY_UPDATE #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "pack_common.h" int32_t PackKeyUpdate(const TLS_Ctx *ctx, PackPacket *pkt) { uint8_t keyUpdateValue = (uint8_t)ctx->keyUpdateType; return PackAppendUint8ToBuf(pkt, keyUpdateValue); } #endif /* HITLS_TLS_FEATURE_KEY_UPDATE */
2301_79861745/bench_create
tls/handshake/pack/src/pack_key_update.c
C
unknown
1,021
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 PACK_MSG_H #define PACK_MSG_H #include <stdint.h> #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Pack ClientHello message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackClientHello(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack HelloVerifyRequest message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackHelloVerifyRequest(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack ServertHello message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackServerHello(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack Encrypted Extensions message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackEncryptedExtensions(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack Tls1.3 Certificate message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13PackCertificate(TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack certificate message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackCertificate(TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack CertificateRequest message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackCertificateRequest(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack Tls1.3 CertificateRequest message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13PackCertificateRequest(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack CertificateVerify message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackCertificateVerify(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack new session ticket message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackNewSessionTicket(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack TLS1.3 new session ticket message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13PackNewSessionTicket(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack ServerKeyExchange message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackServerKeyExchange(TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack ClientKeyExchange message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackClientKeyExchange(TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack Finished message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackFinished(const TLS_Ctx *ctx, PackPacket *pkt); /** * @brief Pack KeyUpdate message * * @param ctx [IN] TLS context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t PackKeyUpdate(const TLS_Ctx *ctx, PackPacket *pkt); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end PACK_MSG_H */
2301_79861745/bench_create
tls/handshake/pack/src/pack_msg.h
C
unknown
4,938
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER) && defined(HITLS_TLS_FEATURE_SESSION_TICKET) #include <stdint.h> #include "securec.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 "pack_common.h" #include "tls.h" #include "hs_ctx.h" #include "custom_extensions.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t PackNewSessionTicket(const TLS_Ctx *ctx, PackPacket *pkt) { HS_Ctx *hsCtx = ctx->hsCtx; /* Pack ticket lifetime hint */ int32_t ret = PackAppendUint32ToBuf(pkt, hsCtx->ticketLifetimeHint); if (ret != HITLS_SUCCESS) { return ret; } /* Pack ticket length */ ret = PackAppendUint16ToBuf(pkt, (uint16_t)hsCtx->ticketSize); if (ret != HITLS_SUCCESS) { return ret; } /* rfc5077 3.3. NewSessionTicket Handshake Message If the server determines that it does not want to include a ticket after including the SessionTicket extension in the ServerHello, it sends a zero-length ticket in the NewSessionTicket handshake message. */ if (hsCtx->ticketSize != 0) { ret = PackAppendDataToBuf(pkt, hsCtx->ticket, hsCtx->ticketSize); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13PackNewSessionTicket(const TLS_Ctx *ctx, PackPacket *pkt) { HS_Ctx *hsCtx = ctx->hsCtx; /* Pack ticket lifetime */ int32_t ret = PackAppendUint32ToBuf(pkt, hsCtx->ticketLifetimeHint); if (ret != HITLS_SUCCESS) { return ret; } /* Pack ticket age add */ ret = PackAppendUint32ToBuf(pkt, hsCtx->ticketAgeAdd); if (ret != HITLS_SUCCESS) { return ret; } /* Pack ticket nonce length (1 byte) */ ret = PackAppendUint8ToBuf(pkt, sizeof(hsCtx->nextTicketNonce)); if (ret != HITLS_SUCCESS) { return ret; } /* Pack ticket nonce (8 bytes) */ ret = PackAppendUint64ToBuf(pkt, hsCtx->nextTicketNonce); if (ret != HITLS_SUCCESS) { return ret; } /* Pack ticket length */ ret = PackAppendUint16ToBuf(pkt, (uint16_t)hsCtx->ticketSize); if (ret != HITLS_SUCCESS) { return ret; } /* In TLS1.3, no empty new session ticket is sent because we ensure that hsCtx->ticketSize is not empty at the invoking point. Therefore, you do not need to check whether hsCtx->ticketSize is empty. */ ret = PackAppendDataToBuf(pkt, hsCtx->ticket, hsCtx->ticketSize); if (ret != HITLS_SUCCESS) { return ret; } /* Pack extensions length field */ uint32_t extensionsLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint16_t), &extensionsLenPosition); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsPackNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET)) { ret = PackCustomExtensions(ctx, pkt, HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET, NULL, 0); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ /* Close extensions length field */ PackCloseUint16Field(pkt, extensionsLenPosition); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER && HITLS_TLS_FEATURE_SESSION_TICKET */
2301_79861745/bench_create
tls/handshake/pack/src/pack_new_session_ticket.c
C
unknown
4,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. */ #include "hitls_build.h" #ifdef HITLS_TLS_HOST_SERVER #include <stdint.h> #include "securec.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_security.h" #include "tls.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "hs_ctx.h" #include "pack_common.h" #include "pack_extensions.h" // Pack the mandatory content of the ServerHello message static int32_t PackServerHelloMandatoryField(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint16_t negotiatedVersion = ctx->negotiatedInfo.version; uint16_t version = #ifdef HITLS_TLS_PROTO_TLS13 (negotiatedVersion == HITLS_VERSION_TLS13) ? HITLS_VERSION_TLS12 : #endif negotiatedVersion; #ifdef HITLS_TLS_FEATURE_SECURITY ret = SECURITY_CfgCheck(&ctx->config.tlsConfig, HITLS_SECURITY_SECOP_VERSION, 0, version, NULL); if (ret != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16940, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CfgCheck fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSECURE_VERSION); ctx->method.sendAlert((TLS_Ctx *)(uintptr_t)ctx, ALERT_LEVEL_FATAL, ALERT_INSUFFICIENT_SECURITY); return HITLS_PACK_UNSECURE_VERSION; } #endif ret = PackAppendUint16ToBuf(pkt, version); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendDataToBuf(pkt, ctx->hsCtx->serverRandom, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_TLS_FEATURE_SESSION_ID) || defined(HITLS_TLS_PROTO_TLS13) HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; ret = PackSessionId(pkt, hsCtx->sessionId, hsCtx->sessionIdSize); if (ret != HITLS_SUCCESS) { (void)memset_s(hsCtx->sessionId, hsCtx->sessionIdSize, 0, hsCtx->sessionIdSize); return ret; } #else // Session recovery is not supported. ret = PackAppendUint8ToBuf(pkt, 0); if (ret != HITLS_SUCCESS) { return ret; } #endif ret = PackAppendUint16ToBuf(pkt, ctx->negotiatedInfo.cipherSuiteInfo.cipherSuite); // cipher suite if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendUint8ToBuf(pkt, 0); // Compression method, currently supports uncompression if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } // Pack the ServertHello message. int32_t PackServerHello(const TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = PackServerHelloMandatoryField(ctx, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15863, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack server hello mandatory content fail.", 0, 0, 0, 0); return ret; } ret = PackServerExtension(ctx, pkt); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15864, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack server hello extension content fail.", 0, 0, 0, 0); return ret; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/pack/src/pack_server_hello.c
C
unknown
3,673
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_TLS_HOST_SERVER #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include <stdint.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 "tls.h" #include "cipher_suite.h" #include "crypt.h" #include "cert.h" #include "hs_ctx.h" #include "hs_common.h" #include "pack_common.h" #if defined(HITLS_TLS_SUITE_KX_ECDHE) || defined(HITLS_TLS_SUITE_KX_DHE) /* Determine whether additional parameter signatures are required. */ static bool IsNeedKeyExchParamSignature(const TLS_Ctx *ctx) { /* Add the parameter signature only when the authentication algorithm is not HITLS_AUTH_NULL for the DHE and ECDHE * cipher suites */ return ((ctx->hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_ECDHE || ctx->hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_DHE) && ctx->negotiatedInfo.cipherSuiteInfo.authAlg != HITLS_AUTH_NULL); } #endif #if defined(HITLS_TLS_SUITE_KX_ECDHE) || defined(HITLS_TLS_SUITE_KX_DHE) static int32_t SignKeyExchParams(TLS_Ctx *ctx, uint8_t *kxData, uint32_t kxDataLen, uint8_t *signBuf, uint32_t *signLen) { uint32_t offset = 0u; HITLS_SignHashAlgo signScheme = ctx->negotiatedInfo.signScheme; HITLS_SignAlgo signAlgo; HITLS_HashAlgo hashAlgo; if (CFG_GetSignParamBySchemes(ctx, signScheme, &signAlgo, &hashAlgo) != true) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15496, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get sign parm fail.", 0, 0, 0, 0); return HITLS_PACK_SIGNATURE_ERR; } uint32_t dataLen; /* Obtain all signature data (random number + server kx content) */ uint8_t *data = HS_PrepareSignData(ctx, kxData, kxDataLen, &dataLen); if (data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15495, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "prepare unsigned data fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } #ifdef HITLS_TLS_PROTO_TLCP11 if (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11) #endif /* HITLS_TLS_PROTO_TLCP11 */ { if (ctx->negotiatedInfo.version >= HITLS_VERSION_TLS12) { /* TLS1.2 and later versions require explicit hash and signature algorithms to be specified in messages, and * TLCP are not written */ BSL_Uint16ToByte(signScheme, signBuf); offset += sizeof(uint16_t); } } /* Temporarily record the position of the signature length in the packet and fill it later */ uint32_t signLenOffset = offset; offset += sizeof(uint16_t); /* Fill signature parameters */ CERT_SignParam signParam = {0}; signParam.signAlgo = signAlgo; signParam.hashAlgo = hashAlgo; signParam.data = data; signParam.dataLen = dataLen; signParam.sign = &signBuf[offset]; signParam.signLen = (uint16_t)(*signLen - offset); /* Fill signature */ HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(ctx->config.tlsConfig.certMgrCtx, false); int32_t ret = SAL_CERT_CreateSign(ctx, privateKey, &signParam); BSL_SAL_FREE(data); if ((ret != HITLS_SUCCESS) || (offset + signParam.signLen > *signLen)) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15497, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "create signature fail.", 0, 0, 0, 0); return HITLS_PACK_SIGNATURE_ERR; } offset += signParam.signLen; BSL_Uint16ToByte((uint16_t)signParam.signLen, &signBuf[signLenOffset]); *signLen = offset; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_ECDHE || HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_ECDHE static uint32_t GetNamedCurveMsgLen(TLS_Ctx *ctx, uint32_t pubKeyLen) { HITLS_Config *config = &(ctx->config.tlsConfig); /* Message length = Curve type (1 byte) + Curve ID (2 byte) + Public key length (1 byte) + Public key + Signature * length (2 byte) + Signature */ uint32_t dataLen = sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint8_t) + pubKeyLen; /* ECDHE_PSK key exchange does not require signature */ if (IsNeedKeyExchParamSignature(ctx)) { HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(config->certMgrCtx, false); uint32_t signatureLen = SAL_CERT_GetSignMaxLen(config, privateKey); if ((signatureLen == 0u) || (signatureLen > MAX_SIGN_SIZE)) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15499, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack ske error: invalid signature length = %u.", signatureLen, 0, 0, 0); return 0; } dataLen += sizeof(uint16_t) + signatureLen; /* A signature type needs to be added to TLS1.2/DTLS. The signature type does not need to be transferred */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS12 || ctx->negotiatedInfo.version == HITLS_VERSION_DTLS12) { dataLen += sizeof(uint16_t); } } return dataLen; } static int32_t PackServerKxMsgNamedCurve(TLS_Ctx *ctx, PackPacket *pkt) { KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; HITLS_ECParameters *ecParam = &(kxCtx->keyExchParam.ecdh.curveParams); uint32_t pubKeyLen = SAL_CRYPT_GetCryptLength(ctx, HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN, ecParam->param.namedcurve); if (pubKeyLen == 0u) { BSL_ERR_PUSH_ERROR(HITLS_PACK_INVALID_KX_PUBKEY_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15498, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack ske error: unsupport named curve = %u.", ecParam->param.namedcurve, 0, 0, 0); return HITLS_PACK_INVALID_KX_PUBKEY_LENGTH; } uint32_t dataLen = GetNamedCurveMsgLen(ctx, pubKeyLen); if (dataLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16941, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetNamedCurveMsgLen err", 0, 0, 0, 0); return HITLS_PACK_SIGNATURE_ERR; } uint32_t dataOffset = 0; int32_t ret = PackGetSubBuffer(pkt, 0, &dataOffset, NULL); if (ret != HITLS_SUCCESS) { return ret; } /* Curve type and curve ID. Although these parameters are ignored in the TLCP, they are * filled in to ensure the uniform style. However, the client cannot depend on the value of this parameter */ ret = PackAppendUint8ToBuf(pkt, (uint8_t)(ecParam->type)); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendUint16ToBuf(pkt, (uint16_t)(ecParam->param.namedcurve)); if (ret != HITLS_SUCCESS) { return ret; } /* Public key length and public key content */ uint32_t pubKeyLenOffset = 0; ret = PackStartLengthField(pkt, sizeof(uint8_t), &pubKeyLenOffset); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *pubKeyBuf = NULL; ret = PackReserveBytes(pkt, pubKeyLen, &pubKeyBuf); if (ret != HITLS_SUCCESS) { return ret; } uint32_t pubKeyUsedLen = 0; ret = SAL_CRYPT_EncodeEcdhPubKey(kxCtx->key, pubKeyBuf, pubKeyLen, &pubKeyUsedLen); if (ret != HITLS_SUCCESS || pubKeyLen != pubKeyUsedLen) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15501, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode ecdh key fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } (void)PackSkipBytes(pkt, pubKeyUsedLen); PackCloseUint8Field(pkt, pubKeyLenOffset); if (IsNeedKeyExchParamSignature(ctx)) { uint32_t signDataLen = 0; (void)PackGetSubBuffer(pkt, dataOffset, &signDataLen, NULL); uint32_t signatureLen = dataLen - signDataLen; uint8_t *signBuf = NULL; ret = PackReserveBytes(pkt, signatureLen, &signBuf); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *signData = NULL; (void)PackGetSubBuffer(pkt, dataOffset, &signDataLen, &signData); ret = SignKeyExchParams(ctx, signData, signDataLen, signBuf, &signatureLen); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15502, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "signature fail.", 0, 0, 0, 0); return HITLS_PACK_SIGNATURE_ERR; } (void)PackSkipBytes(pkt, signatureLen); } return HITLS_SUCCESS; } static int32_t PackServerKxMsgEcdhe(TLS_Ctx *ctx, PackPacket *pkt) { HITLS_ECCurveType type = ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type; switch (type) { case HITLS_EC_CURVE_TYPE_NAMED_CURVE: return PackServerKxMsgNamedCurve(ctx, pkt); default: break; } BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSUPPORT_KX_CURVE_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15503, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unsupport key exchange curve type.", 0, 0, 0, 0); return HITLS_PACK_UNSUPPORT_KX_CURVE_TYPE; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_PROTO_TLCP11 static int32_t PackEccSignature(TLS_Ctx *ctx, PackPacket *pkt, HITLS_SignAlgo signAlgo, HITLS_HashAlgo hashAlgo, uint8_t *data, uint32_t dataLen) { HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(ctx->config.tlsConfig.certMgrCtx, false); uint32_t signatureLen = SAL_CERT_GetSignMaxLen(&(ctx->config.tlsConfig), privateKey); if ((signatureLen == 0u) || (signatureLen > MAX_SIGN_SIZE)) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15508, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid signature length.", 0, 0, 0, 0); return HITLS_PACK_SIGNATURE_ERR; } /* Fill signature parameters */ CERT_SignParam signParam = {0}; signParam.signAlgo = signAlgo; signParam.hashAlgo = hashAlgo; signParam.data = data; signParam.dataLen = dataLen; uint8_t *signBuf = NULL; int32_t ret = PackReserveBytes(pkt, signatureLen, &signBuf); if (ret != HITLS_SUCCESS) { return ret; } signParam.sign = signBuf; signParam.signLen = signatureLen; ret = SAL_CERT_CreateSign(ctx, privateKey, &signParam); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); return RETURN_ERROR_NUMBER_PROCESS(HITLS_PACK_SIGNATURE_ERR, BINLOG_ID16221, "create sm2 signature fail"); } ret = PackSkipBytes(pkt, signParam.signLen); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } /* This function is invoked only by the TLCP */ static int32_t PackServerKxMsgEcc(TLS_Ctx *ctx, PackPacket *pkt) { uint8_t *data = NULL; uint32_t dataLen, certLen; uint8_t *encCert = SAL_CERT_SrvrGmEncodeEncCert(ctx, &certLen); if (encCert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_ENCODE); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_ENCODE, BINLOG_ID16942, "SAL_CERT_SrvrGmEncodeEncCert fail"); } /* Obtain all signature data (random number + server kx content) */ data = HS_PrepareSignDataTlcp(ctx, encCert, certLen, &dataLen); BSL_SAL_FREE(encCert); if (data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16219, "prepare unsigned data fail"); } HITLS_SignAlgo signAlgo; HITLS_HashAlgo hashAlgo; if (!CFG_GetSignParamBySchemes(ctx, ctx->negotiatedInfo.signScheme, &signAlgo, &hashAlgo)) { BSL_SAL_FREE(data); BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); return RETURN_ERROR_NUMBER_PROCESS(HITLS_PACK_SIGNATURE_ERR, BINLOG_ID16220, "get sign parm fail"); } /* The hash and signature algorithms do not need to be explicitly specified in messages by TLCP. The hash algorithm * obtained based on signScheme is used. */ uint32_t signLenPosition = 0u; /* The records the position of the signature length in the message temporarily, and then fills the signature length in the message later */ int32_t ret = PackStartLengthField(pkt, sizeof(uint16_t), &signLenPosition); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(data); return ret; } ret = PackEccSignature(ctx, pkt, signAlgo, hashAlgo, data, dataLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(data); return ret; } PackCloseUint16Field(pkt, signLenPosition); BSL_SAL_FREE(data); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLCP11 */ #ifdef HITLS_TLS_SUITE_KX_DHE static int32_t PackKxPrimaryData(const TLS_Ctx *ctx, PackPacket *pkt) { KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; DhParam *dh = &ctx->hsCtx->kxCtx->keyExchParam.dh; uint32_t pubkeyLen = dh->plen; uint16_t plen = dh->plen; uint16_t glen = dh->glen; int32_t ret = PackAppendUint16ToBuf(pkt, plen); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendDataToBuf(pkt, dh->p, plen); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendUint16ToBuf(pkt, glen); if (ret != HITLS_SUCCESS) { return ret; } ret = PackAppendDataToBuf(pkt, dh->g, glen); if (ret != HITLS_SUCCESS) { return ret; } uint32_t pubKeyLenPosition = 0u; ret = PackStartLengthField(pkt, sizeof(uint16_t), &pubKeyLenPosition); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *reservedBuf = NULL; ret = PackReserveBytes(pkt, pubkeyLen, &reservedBuf); if (ret != HITLS_SUCCESS) { return ret; } ret = SAL_CRYPT_EncodeDhPubKey(kxCtx->key, reservedBuf, pubkeyLen, &pubkeyLen); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_DH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15506, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode dhe key fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_DH_KEY; } ret = PackSkipBytes(pkt, pubkeyLen); if (ret != HITLS_SUCCESS) { return ret; } PackCloseUint16Field(pkt, pubKeyLenPosition); return HITLS_SUCCESS; } static int32_t PackServerKxMsgDhePre(TLS_Ctx *ctx, uint32_t *signatureLen) { if (IsNeedKeyExchParamSignature(ctx)) { HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(ctx->config.tlsConfig.certMgrCtx, false); *signatureLen = SAL_CERT_GetSignMaxLen(&(ctx->config.tlsConfig), privateKey); if ((*signatureLen == 0u) || (*signatureLen > MAX_SIGN_SIZE)) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15508, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid signature length.", 0, 0, 0, 0); return HITLS_PACK_SIGNATURE_ERR; } } return HITLS_SUCCESS; } static int32_t GetDheParameterLen(TLS_Ctx *ctx, uint32_t *outLen) { int32_t ret = HITLS_SUCCESS; uint32_t dataLen = 0; DhParam *dh = &ctx->hsCtx->kxCtx->keyExchParam.dh; uint32_t pubkeyLen = dh->plen; uint16_t plen = dh->plen; uint16_t glen = dh->glen; if (pubkeyLen == 0u) { BSL_ERR_PUSH_ERROR(HITLS_PACK_INVALID_KX_PUBKEY_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15507, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid key exchange pubKey length.", 0, 0, 0, 0); return HITLS_PACK_INVALID_KX_PUBKEY_LENGTH; } /* DHE_PSK and ANON_DH do not need signatures */ uint32_t signatureLen = 0; ret = PackServerKxMsgDhePre(ctx, &signatureLen); if (ret != HITLS_SUCCESS) { return ret; } dataLen = sizeof(uint16_t) + plen + sizeof(uint16_t) + glen + sizeof(uint16_t) + pubkeyLen; if (IsNeedKeyExchParamSignature(ctx)) { dataLen += (sizeof(uint16_t) + signatureLen); } #if defined(HITLS_TLS_PROTO_TLS12) || defined(HITLS_TLS_PROTO_DTLS12) if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS12 || ctx->negotiatedInfo.version == HITLS_VERSION_DTLS12) { dataLen += sizeof(uint16_t); // TLS1.2/DTLS needs to add a signature type } #endif /* HITLS_TLS_PROTO_TLS12 || HITLS_TLS_PROTO_DTLS12 */ *outLen = dataLen; return HITLS_SUCCESS; } static int32_t PackServerKxMsgDhe(TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; uint32_t dataLen = 0; ret = GetDheParameterLen(ctx, &dataLen); if (ret != HITLS_SUCCESS) { return ret; } /* Fill the following values in sequence: plen, p, glen, g, pubkeylen, pubkey, signature len, and signature */ uint32_t dataOffset = 0; ret = PackGetSubBuffer(pkt, 0, &dataOffset, NULL); if (ret != HITLS_SUCCESS) { return ret; } ret = PackKxPrimaryData(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } if (IsNeedKeyExchParamSignature(ctx)) { uint32_t signDataLen = 0; (void)PackGetSubBuffer(pkt, dataOffset, &signDataLen, NULL); uint32_t signLen = dataLen - signDataLen; uint8_t *signBuf = NULL; ret = PackReserveBytes(pkt, signLen, &signBuf); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *signData = NULL; (void)PackGetSubBuffer(pkt, dataOffset, &signDataLen, &signData); ret = SignKeyExchParams(ctx, signData, signDataLen, signBuf, &signLen); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_PACK_SIGNATURE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15510, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "kx msg signature fail. ret %d", ret, 0, 0, 0); return HITLS_PACK_SIGNATURE_ERR; } ret = PackSkipBytes(pkt, signLen); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_FEATURE_PSK static int32_t PackServerKxMsgPskIdentityHint(const TLS_Ctx *ctx, PackPacket *pkt) { uint8_t *pskIdentityHint = ctx->config.tlsConfig.pskIdentityHint; /* The length of hintSize <= HITLS_IDENTITY_HINT_MAX_SIZE is ensured during configuration. Therefore, the length of * uint16_t can be forcibly converted to the length of uint16_t */ uint16_t pskIdentityHintSize = (uint16_t)ctx->config.tlsConfig.hintSize; /* append identity hint */ /* for dhe_psk, ecdhe_psk, msg must contain the length of hint even if there is no hint to provide */ int32_t ret = PackAppendUint16ToBuf(pkt, pskIdentityHintSize); if (ret != HITLS_SUCCESS) { return ret; } if (pskIdentityHint != NULL && pskIdentityHintSize > 0) { ret = PackAppendDataToBuf(pkt, pskIdentityHint, pskIdentityHintSize); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PSK */ // Pack the ServerKeyExchange message. int32_t PackServerKeyExchange(TLS_Ctx *ctx, PackPacket *pkt) { int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_PSK /* pack psk identity hint before dynamic key */ if (IsPskNegotiation(ctx)) { ret = PackServerKxMsgPskIdentityHint(ctx, pkt); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_PSK */ /* Pack a key exchange message */ switch (ctx->negotiatedInfo.cipherSuiteInfo.kxAlg) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: case HITLS_KEY_EXCH_ECDHE_PSK: ret = PackServerKxMsgEcdhe(ctx, pkt); break; #endif #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = PackServerKxMsgDhe(ctx, pkt); break; #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_RSA case HITLS_KEY_EXCH_RSA_PSK: case HITLS_KEY_EXCH_PSK: /* for psk and rsa_psk nego, ServerKeyExchange msg contains only identity hint */ ret = HITLS_SUCCESS; break; #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: ret = PackServerKxMsgEcc(ctx, pkt); break; #endif default: BSL_ERR_PUSH_ERROR(HITLS_PACK_UNSUPPORT_KX_ALG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15513, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unsupport key exchange algorithm when pack server key exchange msg.", 0, 0, 0, 0); return HITLS_PACK_UNSUPPORT_KX_ALG; } return ret; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/pack/src/pack_server_key_exchange.c
C
unknown
21,382
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 PARSE_H #define PARSE_H #include "hs_msg.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Parse handshake message header * * @param ctx [IN] TLS context * @param data [IN] Handshake message * @param len [IN] Message length * @param hsMsgInfo [OUT] Parsed handshake message header * * @return HITLS_SUCCESS * For other error codes, see hitls_error.h */ int32_t HS_ParseMsgHeader(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_MsgInfo *hsMsgInfo); /** * @brief Parse the whole handshake message * Used in pairs with HS_CleanMsg. After parsing, the data needs to be cleaned. * * @param ctx [IN] TLS context * @param hsMsgInfo [IN] Handshake message * @param hsMsg [OUT] Parsed complete handshake message * * @return HITLS_SUCCESS * For other error codes, see hitls_error.h */ int32_t HS_ParseMsg(TLS_Ctx *ctx, const HS_MsgInfo *hsMsgInfo, HS_Msg *hsMsg); /** * @brief Clean handshake messages * Used in pairs with HS_ParseMsg to release the memory allocated in hsMsg * * @param hsMsg [IN] Handshake message */ void HS_CleanMsg(HS_Msg *hsMsg); /** * @brief Check whether the type of the handshake message is expected * * @param ctx [IN] TLS context * @param msgType [IN] Handshake message type * * @return HITLS_SUCCESS * For other error codes, see hitls_error.h */ int32_t CheckHsMsgType(TLS_Ctx *ctx, HS_MsgType msgType); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end PARSE_H */
2301_79861745/bench_create
tls/handshake/parse/include/parse.h
C
unknown
2,093
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_build.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.h" #include "hitls_error.h" #include "hitls_config.h" #include "tls.h" #include "hs.h" #include "hs_common.h" #include "parse_msg.h" #include "parse_common.h" #include "hs_extensions.h" #include "parse_extensions.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif /* HITLS_TLS_FEATURE_INDICATOR */ typedef int32_t (*CheckHsMsgTypeFunc)(TLS_Ctx *ctx, const HS_MsgType msgType); typedef struct { HS_MsgType msgType; CheckHsMsgTypeFunc checkCb; } HsMsgTypeCheck; #ifdef HITLS_TLS_PROTO_DTLS12 static int32_t CheckHelloVerifyRequestType(TLS_Ctx *ctx, const HS_MsgType msgType) { if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && msgType == SERVER_HELLO) { (void)HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO); return HITLS_SUCCESS; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17022, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Check hvr Type fail", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } #endif static int32_t CheckServerHelloType(TLS_Ctx *ctx, const HS_MsgType msgType) { /* In DTLS, When client try to receive ServerHello message, it doesn't know if server enables * isSupportDtlsCookieExchange. If client receives HelloVerifyRequest message, also valid */ if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && msgType == HELLO_VERIFY_REQUEST) { (void)HS_ChangeState(ctx, TRY_RECV_HELLO_VERIFY_REQUEST); return HITLS_SUCCESS; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17331, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckServerHelloType fail", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } static int32_t CheckServerKeyExchangeType(TLS_Ctx *ctx, const HS_MsgType msgType) { /* When the PSK and RSA_PSK are used, whether the ServerKeyExchange message is received depends on whether the * server sends a PSK identity hint */ if (ctx->hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_PSK || ctx->hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_RSA_PSK) { if (msgType == CERTIFICATE_REQUEST) { (void)HS_ChangeState(ctx, TRY_RECV_CERTIFICATE_REQUEST); return HITLS_SUCCESS; } else if (msgType == SERVER_HELLO_DONE) { (void)HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO_DONE); return HITLS_SUCCESS; } } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17025, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckServerKeyExchangeType fail", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } static int32_t CheckCertificateRequestType(TLS_Ctx *ctx, const HS_MsgType msgType) { uint32_t version = HS_GetVersion(ctx); if (version == HITLS_VERSION_TLS13) { if (msgType == CERTIFICATE) { (void)HS_ChangeState(ctx, TRY_RECV_CERTIFICATE); return HITLS_SUCCESS; } } else { if (msgType == SERVER_HELLO_DONE) { (void)HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO_DONE); return HITLS_SUCCESS; } } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17026, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Check cert reqType fail", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } static const HsMsgTypeCheck g_checkHsMsgTypeList[] = { [TRY_RECV_CLIENT_HELLO] = {.msgType = CLIENT_HELLO, .checkCb = NULL}, [TRY_RECV_SERVER_HELLO] = {.msgType = SERVER_HELLO, .checkCb = CheckServerHelloType}, #ifdef HITLS_TLS_PROTO_DTLS12 [TRY_RECV_HELLO_VERIFY_REQUEST] = {.msgType = HELLO_VERIFY_REQUEST, .checkCb = CheckHelloVerifyRequestType}, #endif [TRY_RECV_ENCRYPTED_EXTENSIONS] = {.msgType = ENCRYPTED_EXTENSIONS, .checkCb = NULL}, [TRY_RECV_CERTIFICATE] = {.msgType = CERTIFICATE, .checkCb = NULL}, [TRY_RECV_SERVER_KEY_EXCHANGE] = {.msgType = SERVER_KEY_EXCHANGE, .checkCb = CheckServerKeyExchangeType}, [TRY_RECV_CERTIFICATE_REQUEST] = {.msgType = CERTIFICATE_REQUEST, .checkCb = CheckCertificateRequestType}, [TRY_RECV_SERVER_HELLO_DONE] = {.msgType = SERVER_HELLO_DONE, .checkCb = NULL}, [TRY_RECV_CLIENT_KEY_EXCHANGE] = {.msgType = CLIENT_KEY_EXCHANGE, .checkCb = NULL}, [TRY_RECV_CERTIFICATE_VERIFY] = {.msgType = CERTIFICATE_VERIFY, .checkCb = NULL}, [TRY_RECV_NEW_SESSION_TICKET] = {.msgType = NEW_SESSION_TICKET, .checkCb = NULL}, [TRY_RECV_FINISH] = {.msgType = FINISHED, .checkCb = NULL}, [TRY_RECV_KEY_UPDATE] = {.msgType = KEY_UPDATE, .checkCb = NULL}, [TRY_RECV_HELLO_REQUEST] = {.msgType = HELLO_REQUEST, .checkCb = NULL}, }; int32_t CheckHsMsgType(TLS_Ctx *ctx, HS_MsgType msgType) { if (ctx->state != CM_STATE_HANDSHAKING && ctx->state != CM_STATE_RENEGOTIATION) { return HITLS_SUCCESS; } if ((msgType == HELLO_REQUEST) && (ctx->isClient)) { /* The HelloRequest message may appear at any time during the handshake. The client should ignore this message */ return HITLS_SUCCESS; } HS_Ctx *hsCtx = ctx->hsCtx; const char *expectedMsg = NULL; if (msgType != g_checkHsMsgTypeList[hsCtx->state].msgType) { if (g_checkHsMsgTypeList[hsCtx->state].checkCb == NULL || g_checkHsMsgTypeList[hsCtx->state].checkCb(ctx, msgType) != HITLS_SUCCESS) { expectedMsg = HS_GetMsgTypeStr(g_checkHsMsgTypeList[hsCtx->state].msgType); } } if (msgType == FINISHED && HS_GetVersion(ctx) != HITLS_VERSION_TLS13 && !(ctx->state == CM_STATE_HANDSHAKING && ctx->preState == CM_STATE_TRANSPORTING)) { bool isCcsRecv = ctx->method.isRecvCCS(ctx); if (isCcsRecv != true) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15349, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "recv finish but haven't recv ccs", 0, 0, 0, 0); expectedMsg = HS_GetMsgTypeStr(FINISHED); } } if (expectedMsg != NULL) { BSL_LOG_BINLOG_VARLEN(BINLOG_ID16148, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Handshake state expect %s", expectedMsg); BSL_LOG_BINLOG_VARLEN(BINLOG_ID16149, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, ", but got %s.", HS_GetMsgTypeStr(msgType)); return ParseErrorProcess(ctx, HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE, 0, NULL, ALERT_UNEXPECTED_MESSAGE); } return HITLS_SUCCESS; } static int32_t CheckHsMsgLen(TLS_Ctx *ctx, HS_MsgInfo *hsMsgInfo) { int32_t ret = HITLS_SUCCESS; uint32_t headerLen = IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) ? DTLS_HS_MSG_HEADER_SIZE : HS_MSG_HEADER_SIZE; uint32_t hsMsgOfSpecificTypeMaxSize = HS_MaxMessageSize(ctx, hsMsgInfo->type); hsMsgOfSpecificTypeMaxSize = hsMsgOfSpecificTypeMaxSize > HITLS_HS_BUFFER_SIZE_LIMIT - headerLen ? HITLS_HS_BUFFER_SIZE_LIMIT - headerLen : hsMsgOfSpecificTypeMaxSize; if (hsMsgInfo->length > hsMsgOfSpecificTypeMaxSize) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16161, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "(D)TLS HS msg type: %d, parsed length: %u, max length: %u.", (int)hsMsgInfo->type, hsMsgInfo->length, hsMsgOfSpecificTypeMaxSize, 0); return ParseErrorProcess(ctx, HITLS_PARSE_EXCESSIVE_MESSAGE_SIZE, 0, NULL, ALERT_ILLEGAL_PARAMETER); } ret = HS_GrowMsgBuf(ctx, headerLen + hsMsgInfo->length, true); if (ret != HITLS_SUCCESS) { return ret; } hsMsgInfo->rawMsg = ctx->hsCtx->msgBuf; hsMsgInfo->headerAndBodyLen = headerLen + hsMsgInfo->length; return ret; } #ifdef HITLS_TLS_PROTO_DTLS12 static int32_t DtlsParseHsMsgHeader(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_MsgInfo *hsMsgInfo) { const char *logStr = BINGLOG_STR("parse DTLS handshake msg header failed."); if (len < DTLS_HS_MSG_HEADER_SIZE) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15599, logStr, ALERT_DECODE_ERROR); } hsMsgInfo->type = data[0]; /* The 0 byte is the handshake message type */ if (hsMsgInfo->type >= HS_MSG_TYPE_END) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16123, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DTLS invalid message type: %d.", hsMsgInfo->type, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG; } hsMsgInfo->length = BSL_ByteToUint24(&data[DTLS_HS_MSGLEN_ADDR]); hsMsgInfo->sequence = BSL_ByteToUint16(&data[DTLS_HS_MSGSEQ_ADDR]); hsMsgInfo->fragmentOffset = BSL_ByteToUint24(&data[DTLS_HS_FRAGMENT_OFFSET_ADDR]); hsMsgInfo->fragmentLength = BSL_ByteToUint24(&data[DTLS_HS_FRAGMENT_LEN_ADDR]); if (((hsMsgInfo->fragmentLength + hsMsgInfo->fragmentOffset) > hsMsgInfo->length) || ((hsMsgInfo->length != 0) && (hsMsgInfo->fragmentLength == 0))) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15600, logStr, ALERT_DECODE_ERROR); } return CheckHsMsgLen(ctx, hsMsgInfo); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS static int32_t TlsParseHsMsgHeader(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_MsgInfo *hsMsgInfo) { const char *logStr = BINGLOG_STR("parse TLS handshake msg header failed."); if (len < HS_MSG_HEADER_SIZE) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15601, logStr, ALERT_DECODE_ERROR); } hsMsgInfo->type = data[0]; if (hsMsgInfo->type >= HS_MSG_TYPE_END) { return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG, BINLOG_ID16160, logStr, ALERT_UNEXPECTED_MESSAGE); } int32_t ret = CheckHsMsgType(ctx, hsMsgInfo->type); if (ret != HITLS_SUCCESS) { return ret; } hsMsgInfo->length = BSL_ByteToUint24(data + sizeof(uint8_t)); /* Parse handshake body length */ hsMsgInfo->sequence = 0; /* TLS does not have this field */ hsMsgInfo->fragmentOffset = 0; /* TLS does not have this field */ hsMsgInfo->fragmentLength = 0; /* TLS does not have this field */ return CheckHsMsgLen(ctx, hsMsgInfo); } #endif /* HITLS_TLS_PROTO_TLS */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t ParseHandShakeMsg(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_Msg *hsMsg) { switch (hsMsg->type) { case CLIENT_HELLO: return ParseClientHello(ctx, data, len, hsMsg); case SERVER_HELLO: return ParseServerHello(ctx, data, len, hsMsg); case HELLO_VERIFY_REQUEST: return ParseHelloVerifyRequest(ctx, data, len, hsMsg); case CERTIFICATE: return ParseCertificate(ctx, data, len, hsMsg); case SERVER_KEY_EXCHANGE: return ParseServerKeyExchange(ctx, data, len, hsMsg); case CERTIFICATE_REQUEST: return ParseCertificateRequest(ctx, data, len, hsMsg); case CLIENT_KEY_EXCHANGE: return ParseClientKeyExchange(ctx, data, len, hsMsg); case CERTIFICATE_VERIFY: return ParseCertificateVerify(ctx, data, len, hsMsg); #ifdef HITLS_TLS_FEATURE_SESSION_TICKET case NEW_SESSION_TICKET: return ParseNewSessionTicket(ctx, data, len, hsMsg); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ case FINISHED: return ParseFinished(ctx, data, len, hsMsg); case HELLO_REQUEST: case SERVER_HELLO_DONE: if (len != 0u) { BSL_LOG_BINLOG_VARLEN(BINLOG_ID15603, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "msg %s", HS_GetMsgTypeStr(hsMsg->type)); return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15611, BINGLOG_STR("length is not zero"), ALERT_ILLEGAL_PARAMETER); } return HITLS_SUCCESS; default: break; } BSL_ERR_PUSH_ERROR(HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15604, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dtls parse handshake msg error, unsupport type[%d].", hsMsg->type, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13ParseHandShakeMsg(TLS_Ctx *ctx, const uint8_t *hsBodyData, uint32_t hsBodyLen, HS_Msg *hsMsg) { switch (hsMsg->type) { #ifdef HITLS_TLS_HOST_SERVER case CLIENT_HELLO: return ParseClientHello(ctx, hsBodyData, hsBodyLen, hsMsg); #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_HOST_CLIENT case SERVER_HELLO: return ParseServerHello(ctx, hsBodyData, hsBodyLen, hsMsg); case ENCRYPTED_EXTENSIONS: return ParseEncryptedExtensions(ctx, hsBodyData, hsBodyLen, hsMsg); case CERTIFICATE_REQUEST: return Tls13ParseCertificateRequest(ctx, hsBodyData, hsBodyLen, hsMsg); case NEW_SESSION_TICKET: return ParseNewSessionTicket(ctx, hsBodyData, hsBodyLen, hsMsg); #endif /* HITLS_TLS_HOST_CLIENT */ case CERTIFICATE: return Tls13ParseCertificate(ctx, hsBodyData, hsBodyLen, hsMsg); case CERTIFICATE_VERIFY: return ParseCertificateVerify(ctx, hsBodyData, hsBodyLen, hsMsg); case FINISHED: return ParseFinished(ctx, hsBodyData, hsBodyLen, hsMsg); #ifdef HITLS_TLS_FEATURE_KEY_UPDATE case KEY_UPDATE: return ParseKeyUpdate(ctx, hsBodyData, hsBodyLen, hsMsg); #endif /* HITLS_TLS_FEATURE_KEY_UPDATE */ case HELLO_REQUEST: if (hsBodyLen != 0u) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15611, BINGLOG_STR("hello request length is not zero"), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; default: break; } BSL_ERR_PUSH_ERROR(HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15605, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "recv unsupport handshake msg type[%d].", hsMsg->type, 0, 0, 0); return HITLS_PARSE_UNSUPPORT_HANDSHAKE_MSG; } #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t HS_ParseMsgHeader(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_MsgInfo *hsMsgInfo) { if ((ctx == NULL) || (ctx->method.sendAlert == NULL) || (data == NULL) || (hsMsgInfo == NULL)) { return ParseErrorProcess(ctx, HITLS_INTERNAL_EXCEPTION, BINLOG_ID15606, BINGLOG_STR("null input parameter"), ALERT_UNKNOWN); } uint32_t version = HS_GetVersion(ctx); switch (version) { #ifdef HITLS_TLS_PROTO_TLS case HITLS_VERSION_TLS12: case HITLS_VERSION_TLS13: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_VERSION_TLCP_DTLCP11: #if defined(HITLS_TLS_PROTO_DTLCP11) if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsParseHsMsgHeader(ctx, data, len, hsMsgInfo); } #endif #endif return TlsParseHsMsgHeader(ctx, data, len, hsMsgInfo); #endif /* HITLS_TLS_PROTO_TLS */ #ifdef HITLS_TLS_PROTO_DTLS12 case HITLS_VERSION_DTLS12: return DtlsParseHsMsgHeader(ctx, data, len, hsMsgInfo); #endif default: break; } BSL_ERR_PUSH_ERROR(HITLS_PARSE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15607, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unsupport msg header version[0x%x].", version, 0, 0, 0); return HITLS_PARSE_UNSUPPORT_VERSION; } int32_t HS_ParseMsg(TLS_Ctx *ctx, const HS_MsgInfo *hsMsgInfo, HS_Msg *hsMsg) { if ((ctx == NULL) || (ctx->method.sendAlert == NULL) || (hsMsgInfo == NULL) || (hsMsgInfo->rawMsg == NULL) || (hsMsg == NULL)) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15608, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the input parameter pointer is null.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } hsMsg->type = hsMsgInfo->type; hsMsg->length = hsMsgInfo->length; hsMsg->sequence = hsMsgInfo->sequence; hsMsg->fragmentOffset = hsMsgInfo->fragmentOffset; hsMsg->fragmentLength = hsMsgInfo->fragmentLength; uint32_t version = HS_GetVersion(ctx); switch (version) { #ifdef HITLS_TLS_PROTO_TLS_BASIC case HITLS_VERSION_TLS12: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_VERSION_TLCP_DTLCP11: #if defined(HITLS_TLS_PROTO_DTLCP11) if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return ParseHandShakeMsg(ctx, &hsMsgInfo->rawMsg[DTLS_HS_MSG_HEADER_SIZE], hsMsgInfo->length, hsMsg); } #endif #endif return ParseHandShakeMsg(ctx, &hsMsgInfo->rawMsg[HS_MSG_HEADER_SIZE], hsMsgInfo->length, hsMsg); #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 case HITLS_VERSION_TLS13: return Tls13ParseHandShakeMsg(ctx, &hsMsgInfo->rawMsg[HS_MSG_HEADER_SIZE], hsMsgInfo->length, hsMsg); #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_DTLS12 case HITLS_VERSION_DTLS12: return ParseHandShakeMsg(ctx, &hsMsgInfo->rawMsg[DTLS_HS_MSG_HEADER_SIZE], hsMsgInfo->length, hsMsg); #endif default: break; } BSL_ERR_PUSH_ERROR(HITLS_PARSE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15609, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unsupport handshake msg version[0x%x].", version, 0, 0, 0); return HITLS_PARSE_UNSUPPORT_VERSION; } void HS_CleanMsg(HS_Msg *hsMsg) { if (hsMsg == NULL) { return; } switch (hsMsg->type) { #ifdef HITLS_TLS_HOST_SERVER case CLIENT_HELLO: return CleanClientHello(&hsMsg->body.clientHello); #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) case CLIENT_KEY_EXCHANGE: return CleanClientKeyExchange(&hsMsg->body.clientKeyExchange); #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_HOST_CLIENT case SERVER_HELLO: return CleanServerHello(&hsMsg->body.serverHello); case HELLO_VERIFY_REQUEST: return CleanHelloVerifyRequest(&hsMsg->body.helloVerifyReq); case CERTIFICATE_REQUEST: return CleanCertificateRequest(&hsMsg->body.certificateReq); #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) case SERVER_KEY_EXCHANGE: return CleanServerKeyExchange(&hsMsg->body.serverKeyExchange); #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 case ENCRYPTED_EXTENSIONS: return CleanEncryptedExtensions(&hsMsg->body.encryptedExtensions); #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET case NEW_SESSION_TICKET: return CleanNewSessionTicket(&hsMsg->body.newSessionTicket); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #endif /* HITLS_TLS_HOST_CLIENT */ case CERTIFICATE: return CleanCertificate(&hsMsg->body.certificate); case CERTIFICATE_VERIFY: return CleanCertificateVerify(&hsMsg->body.certificateVerify); case FINISHED: return CleanFinished(&hsMsg->body.finished); case KEY_UPDATE: case HELLO_REQUEST: case SERVER_HELLO_DONE: return; default: break; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15610, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "clean unsupport handshake msg type[%d].", hsMsg->type, 0, 0, 0); return; } #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB int32_t HITLS_ClientHelloGetLegacyVersion(HITLS_Ctx *ctx, uint16_t *version) { if (ctx == NULL || version == NULL) { return HITLS_NULL_INPUT; } if (ctx->hsCtx == NULL || ctx->hsCtx->hsMsg == NULL || ctx->hsCtx->hsMsg->type != CLIENT_HELLO) { return HITLS_CALLBACK_CLIENT_HELLO_INVALID_CALL; } *version = ctx->hsCtx->hsMsg->body.clientHello.version; return HITLS_SUCCESS; } int32_t HITLS_ClientHelloGetRandom(HITLS_Ctx *ctx, uint8_t **out, uint8_t *outlen) { if (ctx == NULL || out == NULL || outlen == NULL) { return HITLS_NULL_INPUT; } if (ctx->hsCtx == NULL || ctx->hsCtx->hsMsg == NULL || ctx->hsCtx->hsMsg->type != CLIENT_HELLO) { return HITLS_CALLBACK_CLIENT_HELLO_INVALID_CALL; } *out = ctx->hsCtx->hsMsg->body.clientHello.randomValue; *outlen = RANDOM_SIZE; return HITLS_SUCCESS; } int32_t HITLS_ClientHelloGetSessionID(HITLS_Ctx *ctx, uint8_t **out, uint8_t *outlen) { if (ctx == NULL || out == NULL || outlen == NULL) { return HITLS_NULL_INPUT; } if (ctx->hsCtx == NULL || ctx->hsCtx->hsMsg == NULL || ctx->hsCtx->hsMsg->type != CLIENT_HELLO) { return HITLS_CALLBACK_CLIENT_HELLO_INVALID_CALL; } *out = ctx->hsCtx->hsMsg->body.clientHello.sessionId; *outlen = ctx->hsCtx->hsMsg->body.clientHello.sessionIdSize; return HITLS_SUCCESS; } int32_t HITLS_ClientHelloGetCiphers(HITLS_Ctx *ctx, uint16_t **out, uint16_t *outlen) { if (ctx == NULL || out == NULL || outlen == NULL) { return HITLS_NULL_INPUT; } if (ctx->hsCtx == NULL || ctx->hsCtx->hsMsg == NULL || ctx->hsCtx->hsMsg->type != CLIENT_HELLO) { return HITLS_CALLBACK_CLIENT_HELLO_INVALID_CALL; } *out = ctx->hsCtx->hsMsg->body.clientHello.cipherSuites; *outlen = ctx->hsCtx->hsMsg->body.clientHello.cipherSuitesSize; return HITLS_SUCCESS; } int32_t HITLS_ClientHelloGetExtensionsPresent(HITLS_Ctx *ctx, uint16_t **out, uint8_t *outlen) { if (ctx == NULL || out == NULL || outlen == NULL) { return HITLS_NULL_INPUT; } if (ctx->hsCtx == NULL || ctx->hsCtx->hsMsg == NULL || ctx->hsCtx->hsMsg->type != CLIENT_HELLO) { return HITLS_CALLBACK_CLIENT_HELLO_INVALID_CALL; } uint32_t bufOffset = 0u; uint8_t *buf = ctx->hsCtx->hsMsg->body.clientHello.extensionBuff; uint32_t bufLen = ctx->hsCtx->hsMsg->body.clientHello.extensionBuffLen; uint16_t *extPresent = BSL_SAL_Malloc(ctx->hsCtx->hsMsg->body.clientHello.extensionCount * sizeof(uint16_t)); if (extPresent == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17355, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc extPresent fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } int32_t ret; uint32_t extPresentCount = 0; while (bufOffset < bufLen) { uint16_t extMsgType = HS_EX_TYPE_END; uint32_t extMsgLen = 0u; ret = ParseExHeader(ctx, &buf[bufOffset], bufLen - bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(extPresent); return ret; } bufOffset += HS_EX_HEADER_LEN; extPresent[extPresentCount++] = extMsgType; bufOffset += extMsgLen; } *out = extPresent; *outlen = ctx->hsCtx->hsMsg->body.clientHello.extensionCount; return HITLS_SUCCESS; } int32_t HITLS_ClientHelloGetExtension(HITLS_Ctx *ctx, uint16_t type, uint8_t **out, uint32_t *outlen) { if (ctx == NULL || out == NULL || outlen == NULL) { return HITLS_NULL_INPUT; } if (ctx->hsCtx == NULL || ctx->hsCtx->hsMsg == NULL || ctx->hsCtx->hsMsg->type != CLIENT_HELLO) { return HITLS_CALLBACK_CLIENT_HELLO_INVALID_CALL; } uint32_t bufOffset = 0u; uint8_t *buf = ctx->hsCtx->hsMsg->body.clientHello.extensionBuff; uint32_t bufLen = ctx->hsCtx->hsMsg->body.clientHello.extensionBuffLen; int32_t ret; while (bufOffset < bufLen) { uint16_t extMsgType = HS_EX_TYPE_END; uint32_t extMsgLen = 0u; ret = ParseExHeader(ctx, &buf[bufOffset], bufLen - bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += HS_EX_HEADER_LEN; if (extMsgType != type) { /* If the extension type is not the one we are looking for, skip it */ bufOffset += extMsgLen; continue; } *out = &buf[bufOffset]; *outlen = extMsgLen; return HITLS_SUCCESS; } return HITLS_CALLBACK_CLIENT_HELLO_EXTENSION_NOT_FOUND; } #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */
2301_79861745/bench_create
tls/handshake/parse/src/parse.c
C
unknown
25,330
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hs_msg.h" #include "hs_common.h" #include "parse_msg.h" #include "parse_common.h" #include "hs_extensions.h" #include "parse_extensions.h" #include "custom_extensions.h" /** * @brief Parse the certificate signature * * @param ctx [IN] TLS context * @param buf [IN] message to be parsed * @param bufLen [IN] buffer length * @param readLen [OUT] Parsed length * * @return Return the memory of the applied certificate. If NULL is returned, the parsing fails. */ int32_t ParseSingleCert(ParsePacket *pkt, CERT_Item **certItem) { uint32_t certLen = 0; /* Obtain the certificate length */ int32_t ret = ParseBytesToUint24(pkt, &certLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15586, BINGLOG_STR("Parse cert data len error."), ALERT_DECODE_ERROR); } if ((certLen == 0) || (certLen > (pkt->bufLen - *pkt->bufOffset))) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15587, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Parse cert data error: data len= %u, cert len= %u.", pkt->bufLen, certLen, 0, 0); return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, 0, NULL, ALERT_DECODE_ERROR); } CERT_Item *item = (CERT_Item*)BSL_SAL_Calloc(1u, sizeof(CERT_Item)); if (item == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15588, BINGLOG_STR("CERT_Item malloc fail."), ALERT_UNKNOWN); } item->next = NULL; item->dataSize = certLen; /* Update the length of the certificate message */ /* Extract the contents of the certificate message */ item->data = BSL_SAL_Malloc(item->dataSize); if (item->data == NULL) { BSL_SAL_FREE(item); return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15589, BINGLOG_STR("item->data malloc fail."), ALERT_UNKNOWN); } (void)memcpy_s(item->data, item->dataSize, &pkt->buf[*pkt->bufOffset], item->dataSize); *pkt->bufOffset += certLen; *certItem = item; return HITLS_SUCCESS; } static int32_t ParseCertExtension(ParsePacket *pkt, CertificateMsg *msg, CERT_Item *item, uint32_t certIndex) { (void)item; (void)certIndex; if (pkt->ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { return HITLS_SUCCESS; } uint16_t certExLen = 0; const char *logStr = BINGLOG_STR("length of certificate extension is incorrect."); int32_t ret = ParseBytesToUint16(pkt, &certExLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15590, logStr, ALERT_DECODE_ERROR); } if (*pkt->bufOffset + certExLen > pkt->bufLen) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16235, logStr, ALERT_DECODE_ERROR); } uint32_t offset = 0; while (offset < certExLen) { uint16_t extMsgType = HS_EX_TYPE_END; uint32_t extMsgLen = 0u; ret = ParseExHeader(pkt->ctx, &pkt->buf[*pkt->bufOffset], pkt->bufLen - *pkt->bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, ret, BINLOG_ID15330, logStr, ALERT_DECODE_ERROR); } *pkt->bufOffset += HS_EX_HEADER_LEN; offset += HS_EX_HEADER_LEN; #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(pkt->ctx), extMsgType, HITLS_EX_TYPE_TLS1_3_CERTIFICATE)) { HITLS_CERT_X509 *cert = SAL_CERT_X509Parse(LIBCTX_FROM_CTX(pkt->ctx), ATTRIBUTE_FROM_CTX(pkt->ctx), &pkt->ctx->config.tlsConfig, item->data, item->dataSize, TLS_PARSE_TYPE_BUFF, TLS_PARSE_FORMAT_ASN1); if (cert == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15331, "X509Parse fail", ALERT_DECODE_ERROR); } ret = ParseCustomExtensions(pkt->ctx, &pkt->buf[*pkt->bufOffset], extMsgType, extMsgLen, HITLS_EX_TYPE_TLS1_3_CERTIFICATE, cert, certIndex); SAL_CERT_X509Free(cert); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, ret, BINLOG_ID15332, "ParseCustomExtensions fail", ALERT_DECODE_ERROR); } } else #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ { msg->extensionTypeMask |= 1ULL << HS_GetExtensionTypeId(extMsgType); } *pkt->bufOffset += extMsgLen; offset += extMsgLen; } if (offset != certExLen) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15463, BINGLOG_STR("extension len error"), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } int32_t ParseCerts(ParsePacket *pkt, HS_Msg *hsMsg) { int32_t ret; CertificateMsg *msg = &hsMsg->body.certificate; CERT_Item *cur = msg->cert; /* Parse the certificate message and save the certificate chain to the structure */ while (*pkt->bufOffset < pkt->bufLen) { CERT_Item *item = NULL; ret = ParseSingleCert(pkt, &item); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_CERT_ERR, BINLOG_ID15591, BINGLOG_STR("parse certificate item fail."), ALERT_UNKNOWN); } /* Add the parsed certificate to the last node in the linked list */ if (msg->cert == NULL) { msg->cert = item; } else if (cur != NULL) { cur->next = item; } cur = item; ret = ParseCertExtension(pkt, msg, item, msg->certCount); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15592, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse certificate extension fail.", 0, 0, 0, 0); return ret; } msg->certCount++; } return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) /** * @brief Parse the certificate message. * * @param ctx [IN] TLS context * @param buf [IN] message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] message structure * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_CERT_ERR Failed to parse the certificate. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseCertificate(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { uint32_t offset = 0; uint32_t allCertsLen = 0; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &offset}; const char *logStr = BINGLOG_STR("length of all certificates is incorrect."); /* Obtain the lengths of all certificates */ int32_t ret = ParseBytesToUint24(&pkt, &allCertsLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15593, logStr, ALERT_DECODE_ERROR); } if (allCertsLen != (pkt.bufLen - CERT_LEN_TAG_SIZE)) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15594, logStr, ALERT_DECODE_ERROR); } /* * The client can send a certificate message without a certificate, so if the total length of the certificate is 0, * it directly returns success; If the client receives a certificate message of length 0, it is determined by the * processing layer, which is only responsible for parsing */ if (allCertsLen == 0) { return HITLS_SUCCESS; } ret = ParseCerts(&pkt, hsMsg); if ((ret != HITLS_SUCCESS) || (*pkt.bufOffset != (allCertsLen + CERT_LEN_TAG_SIZE))) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_CERT_ERR, BINLOG_ID15595, BINGLOG_STR("Certificate msg parse failed."), ALERT_UNKNOWN); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13ParseCertificateReqCtx(ParsePacket *pkt, HS_Msg *hsMsg) { CertificateMsg *certMsg = &hsMsg->body.certificate; /* Obtain the certificates_request_context_length */ uint8_t len = 0; int32_t ret = ParseBytesToUint8(pkt, &len); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16971, BINGLOG_STR("ParseBytesToUint8 fail"), ALERT_DECODE_ERROR); } uint16_t certReqCtxLen = (uint16_t)len; certMsg->certificateReqCtxSize = (uint32_t)certReqCtxLen; /* At least the length and content of the total certificate length of 3 bytes + certificateReqCtx can be parsed */ if (pkt->bufLen < CERT_LEN_TAG_SIZE + certReqCtxLen + sizeof(uint8_t)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16129, BINGLOG_STR("the length of tls13 certificate message is incorrect"), ALERT_DECODE_ERROR); } /* Obtain the certificate_request_context value */ if (certReqCtxLen > 0) { certMsg->certificateReqCtx = BSL_SAL_Calloc(certReqCtxLen, sizeof(uint8_t)); if (certMsg->certificateReqCtx == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15596, BINGLOG_STR("certificateReqCtx malloc fail."), ALERT_UNKNOWN); } (void)memcpy_s(certMsg->certificateReqCtx, certReqCtxLen, &pkt->buf[*pkt->bufOffset], certReqCtxLen); *pkt->bufOffset += certReqCtxLen; } return HITLS_SUCCESS; } /** * @brief Parse the certificate message. * * @param ctx [IN] TLS context * @param buf [IN] message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] message structure * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_CERT_ERR Failed to parse the certificate. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. */ int32_t Tls13ParseCertificate(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { CertificateMsg *certMsg = &hsMsg->body.certificate; uint32_t offset = 0; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &offset}; int32_t ret = Tls13ParseCertificateReqCtx(&pkt, hsMsg); if (ret != HITLS_SUCCESS) { return ret; } uint32_t allCertsLen = 0; ret = ParseBytesToUint24(&pkt, &allCertsLen); if (ret != HITLS_SUCCESS || (allCertsLen != (pkt.bufLen - *pkt.bufOffset))) { CleanCertificate(&hsMsg->body.certificate); return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15597, BINGLOG_STR("length of all tls1.3 certificates is incorrect."), ALERT_DECODE_ERROR); } /* * The client can send a certificate message without a certificate, so if the total length of the certificate is 0, * it directly returns success; If the client receives a certificate message of length 0, it is determined by the * processing layer, which is only responsible for parsing */ if (allCertsLen == 0) { return HITLS_SUCCESS; } ret = ParseCerts(&pkt, hsMsg); if ((ret != HITLS_SUCCESS) || (*pkt.bufOffset != (sizeof(uint8_t) + certMsg->certificateReqCtxSize + CERT_LEN_TAG_SIZE + allCertsLen))) { CleanCertificate(&hsMsg->body.certificate); return ParseErrorProcess(pkt.ctx, HITLS_PARSE_CERT_ERR, BINLOG_ID15598, BINGLOG_STR("Certificate msg parse failed."), ALERT_UNKNOWN); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ // Clear the memory applied for in the certificate message structure. void CleanCertificate(CertificateMsg *msg) { if (msg == NULL) { return; } #ifdef HITLS_TLS_PROTO_TLS13 BSL_SAL_FREE(msg->certificateReqCtx); #endif CERT_Item *next = msg->cert; while (next != NULL) { CERT_Item *temp = next->next; BSL_SAL_FREE(next->data); BSL_SAL_FREE(next); next = temp; } msg->cert = NULL; return; }
2301_79861745/bench_create
tls/handshake/parse/src/parse_certificate.c
C
unknown
12,746
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #include "securec.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 "bsl_list.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_common.h" #include "parse_msg.h" #include "hs_extensions.h" #include "parse_extensions.h" #include "parse_common.h" #include "custom_extensions.h" #if defined(HITLS_TLS_PROTO_TLS12) || defined(HITLS_TLS_PROTO_DTLS12) || defined(HITLS_TLS_PROTO_TLS13) #define SINGLE_SIG_HASH_ALG_SIZE 2u // Parse the signature algorithm field in the certificate request message. static int32_t ParseSignatureAndHashAlgo(ParsePacket *pkt, CertificateRequestMsg *msg) { /* An extension of the same type has already been parsed */ if (msg->haveSignatureAndHashAlgo == true) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_DUPLICATE_EXTENDED_MSG, BINLOG_ID16945, BINGLOG_STR("SignatureAndHashAlgo repeated"), ALERT_ILLEGAL_PARAMETER); } /* Obtain the length of the signature hash algorithm */ uint16_t signatureAndHashAlgLen = 0; const char *logStr = BINGLOG_STR("parse signatureAndHashAlgLen fail."); int32_t ret = ParseBytesToUint16(pkt, &signatureAndHashAlgLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15458, logStr, ALERT_DECODE_ERROR); } if (((uint32_t)signatureAndHashAlgLen > (pkt->bufLen - *pkt->bufOffset)) || ((signatureAndHashAlgLen % SINGLE_SIG_HASH_ALG_SIZE) != 0u) || (signatureAndHashAlgLen == 0u)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15459, logStr, ALERT_DECODE_ERROR); } /* Parse the length of the signature algorithm */ pkt->ctx->peerInfo.signatureAlgorithmsSize = signatureAndHashAlgLen / SINGLE_SIG_HASH_ALG_SIZE; BSL_SAL_FREE(pkt->ctx->peerInfo.signatureAlgorithms); pkt->ctx->peerInfo.signatureAlgorithms = (uint16_t *)BSL_SAL_Malloc(signatureAndHashAlgLen); if (pkt->ctx->peerInfo.signatureAlgorithms == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15460, BINGLOG_STR("signatureAlgorithms malloc fail"), ALERT_UNKNOWN); } /* Extract the signature algorithm */ for (uint16_t index = 0u; index < pkt->ctx->peerInfo.signatureAlgorithmsSize; index++) { pkt->ctx->peerInfo.signatureAlgorithms[index] = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); } msg->signatureAlgorithms = pkt->ctx->peerInfo.signatureAlgorithms; msg->signatureAlgorithmsSize = pkt->ctx->peerInfo.signatureAlgorithmsSize; msg->haveSignatureAndHashAlgo = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS12 || HITLS_TLS_PROTO_DTLS12 || HITLS_TLS_PROTO_TLS13 */ static void CaListNodeInnerDestroy(void *data) { HITLS_TrustedCANode *tmpData = (HITLS_TrustedCANode *)data; BSL_SAL_FREE(tmpData->data); BSL_SAL_FREE(tmpData); return; } void FreeDNList(HITLS_TrustedCAList *caList) { BslList *tmpCaList = (BslList *)caList; BSL_LIST_FREE(tmpCaList, CaListNodeInnerDestroy); return; } HITLS_TrustedCANode *ParseDN(const uint8_t *data, uint32_t len) { HITLS_TrustedCANode *dnNode = (HITLS_TrustedCANode *)BSL_SAL_Calloc(1u, sizeof(HITLS_TrustedCANode)); if (dnNode == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15461, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse CA RDN error, out of memory.", 0, 0, 0, 0); return NULL; } dnNode->caType = HITLS_TRUSTED_CA_X509_NAME; dnNode->data = BSL_SAL_Dump(data, len); if (dnNode->data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15462, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse CA RDN error, dump %u bytes data fail.", len, 0, 0, 0); BSL_SAL_FREE(dnNode); return NULL; } dnNode->dataSize = len; return dnNode; } HITLS_TrustedCAList *ParseDNList(const uint8_t *data, uint32_t len) { int32_t ret; uint32_t dnLen; uint32_t offset = 0u; uint32_t distinguishedNamesLen = len; HITLS_TrustedCANode *tmpNode = NULL; HITLS_TrustedCAList *newCaList = BSL_LIST_New(sizeof(HITLS_TrustedCANode *)); if (newCaList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15547, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc CA List fail.", 0, 0, 0, 0); return NULL; } while (distinguishedNamesLen > sizeof(uint16_t)) { /* Parse the DN length */ dnLen = BSL_ByteToUint16(&data[offset]); offset += sizeof(uint16_t); /* Check whether the DN length is valid. */ if ((dnLen == 0) || dnLen > (len - offset)) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15464, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse CA list error, distinguished name Length = %u, left len = %u.", dnLen, len - offset, 0, 0); goto ERR; } tmpNode = ParseDN(&data[offset], dnLen); if (tmpNode == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16947, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ParseDN fail", 0, 0, 0, 0); goto ERR; } ret = BSL_LIST_AddElement(newCaList, tmpNode, BSL_LIST_POS_END); if (ret != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16948, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "AddElement fail", 0, 0, 0, 0); BSL_SAL_FREE(tmpNode->data); BSL_SAL_FREE(tmpNode); goto ERR; } /* Offset to the next DN data block */ offset += dnLen; distinguishedNamesLen = len - offset; } if (distinguishedNamesLen != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16949, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "distinguishedNamesLen != 0", 0, 0, 0, 0); goto ERR; } return newCaList; ERR: FreeDNList(newCaList); return NULL; } // Parse the identification name field in the certificate request packet. static int32_t ParseDistinguishedName(ParsePacket *pkt, CertificateRequestMsg *msg) { /* An extension of the same type has already been resolved */ if (msg->haveDistinguishedName == true) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_DUPLICATE_EXTENDED_MSG, BINLOG_ID16950, BINGLOG_STR("DistinguishedName repeated"), ALERT_ILLEGAL_PARAMETER); } /* Obtain the DN list length */ uint16_t distinguishedNamesLen = 0; const char *logStr = BINGLOG_STR("parse distinguishedNamesLen fail."); int32_t ret = ParseBytesToUint16(pkt, &distinguishedNamesLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15465, logStr, ALERT_DECODE_ERROR); } if (distinguishedNamesLen != (pkt->bufLen - *pkt->bufOffset)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15466, logStr, ALERT_DECODE_ERROR); } if (distinguishedNamesLen > 0u) { if (pkt->ctx->peerInfo.caList != NULL) { FreeDNList(pkt->ctx->peerInfo.caList); pkt->ctx->peerInfo.caList = NULL; } pkt->ctx->peerInfo.caList = ParseDNList(&pkt->buf[*pkt->bufOffset], distinguishedNamesLen); if (pkt->ctx->peerInfo.caList == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_CA_LIST_ERR, BINLOG_ID16951, BINGLOG_STR("ParseDNList fail"), ALERT_DECODE_ERROR); } *pkt->bufOffset += distinguishedNamesLen; } msg->haveDistinguishedName = true; return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) // Parse the certificate type field in the certificate request message. static int32_t ParseClientCertificateType(ParsePacket *pkt, CertificateRequestMsg *msg) { const char *logStr = BINGLOG_STR("parse certTypesSize fail."); /* Obtain the certificate type length */ int32_t ret = ParseBytesToUint8(pkt, &msg->certTypesSize); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15455, logStr, ALERT_DECODE_ERROR); } if (((uint32_t)msg->certTypesSize > (pkt->bufLen - *pkt->bufOffset)) || (msg->certTypesSize == 0u)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15456, logStr, ALERT_DECODE_ERROR); } /* Obtain the certificate type */ BSL_SAL_FREE(msg->certTypes); msg->certTypes = BSL_SAL_Dump(&pkt->buf[*pkt->bufOffset], msg->certTypesSize); if (msg->certTypes == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15457, BINGLOG_STR("certTypes malloc fail"), ALERT_UNKNOWN); } *pkt->bufOffset += msg->certTypesSize; return HITLS_SUCCESS; } int32_t ParseCertificateRequest(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { uint32_t bufOffset = 0; CertificateRequestMsg *msg = &hsMsg->body.certificateReq; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &bufOffset}; int32_t ret = ParseClientCertificateType(&pkt, msg); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_TLS_PROTO_TLS12) || defined(HITLS_TLS_PROTO_DTLS12) if (pkt.ctx->negotiatedInfo.version >= HITLS_VERSION_TLS12) { ret = ParseSignatureAndHashAlgo(&pkt, msg); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_PROTO_TLS12 || HITLS_TLS_PROTO_DTLS12 */ return ParseDistinguishedName(&pkt, msg); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t ParseCertificateRequestExBody(TLS_Ctx *ctx, uint16_t extMsgType, const uint8_t *buf, uint32_t extMsgLen, CertificateRequestMsg *msg) { uint32_t bufOffset = 0u; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = extMsgLen, .bufOffset = &bufOffset}; switch (extMsgType) { case HS_EX_TYPE_SIGNATURE_ALGORITHMS: return ParseSignatureAndHashAlgo(&pkt, msg); case HS_EX_TYPE_CERTIFICATE_AUTHORITIES: return ParseDistinguishedName(&pkt, msg); default: break; } #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST)) { return ParseCustomExtensions(pkt.ctx, pkt.buf + *pkt.bufOffset, extMsgType, extMsgLen, HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST, NULL, 0); } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ return HITLS_SUCCESS; } int32_t ParseTls13CertificateRequestExtensions(ParsePacket *pkt, CertificateRequestMsg *msg) { if (pkt->bufLen - *pkt->bufOffset == 0u) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15472, BINGLOG_STR("the extension len of tls1.3 can not be 0"), ALERT_DECODE_ERROR); } /* Parse the extended packet on the server */ while (*pkt->bufOffset < pkt->bufLen) { uint16_t extMsgType = HS_EX_TYPE_END; uint32_t extMsgLen = 0u; int32_t ret = ParseExHeader(pkt->ctx, &pkt->buf[*pkt->bufOffset], pkt->bufLen - *pkt->bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { return ret; } *pkt->bufOffset += HS_EX_HEADER_LEN; uint32_t extensionId = HS_GetExtensionTypeId(extMsgType); ret = CheckForDuplicateExtension(msg->extensionTypeMask, extensionId, pkt->ctx); if (ret != HITLS_SUCCESS) { return ret; } msg->extensionTypeMask |= 1ULL << extensionId; ret = ParseCertificateRequestExBody(pkt->ctx, extMsgType, &pkt->buf[*pkt->bufOffset], extMsgLen, msg); if (ret != HITLS_SUCCESS) { return ret; } *pkt->bufOffset += extMsgLen; } /* The extended content is the last field in the CertificateRequest packet. No further data should be displayed. If * the parsed length is inconsistent with the cache length, an error code is returned */ if (*pkt->bufOffset != pkt->bufLen) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15473, BINGLOG_STR("extension len error"), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } int32_t Tls13ParseCertificateRequest(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { uint32_t bufOffset = 0; CertificateRequestMsg *msg = &hsMsg->body.certificateReq; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &bufOffset}; /* Obtain the certificate_request_context_length */ uint8_t certReqCtxLen = 0; int32_t ret = ParseBytesToUint8(&pkt, &certReqCtxLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16130, BINGLOG_STR("tls13 certReq length error"), ALERT_DECODE_ERROR); } msg->certificateReqCtxSize = (uint32_t)certReqCtxLen; /* If the message length is incorrect, an error code is returned. */ if (*pkt.bufOffset + certReqCtxLen + sizeof(uint16_t) > pkt.bufLen) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16962, BINGLOG_STR("certReq length err"), ALERT_DECODE_ERROR); } /* Obtain the certificate_request_context value */ if (certReqCtxLen > 0) { msg->certificateReqCtx = BSL_SAL_Calloc(certReqCtxLen, sizeof(uint8_t)); if (msg->certificateReqCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16963, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc err", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(msg->certificateReqCtx, certReqCtxLen, &pkt.buf[*pkt.bufOffset], certReqCtxLen); *pkt.bufOffset += certReqCtxLen; } /* Obtain the extended message length */ uint16_t exMsgLen = BSL_ByteToUint16(&pkt.buf[*pkt.bufOffset]); *pkt.bufOffset += sizeof(uint16_t); /* If the buffer length does not match the extended length, an error code is returned */ if (exMsgLen != (pkt.bufLen - *pkt.bufOffset)) { BSL_SAL_FREE(msg->certificateReqCtx); msg->certificateReqCtxSize = 0; return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15474, BINGLOG_STR("tls13 external message length error"), ALERT_DECODE_ERROR); } ret = ParseTls13CertificateRequestExtensions(&pkt, msg); if (ret != HITLS_SUCCESS) { CleanCertificateRequest(msg); } return ret; } #endif /* HITLS_TLS_PROTO_TLS13 */ void CleanCertificateRequest(CertificateRequestMsg *msg) { if (msg == NULL) { return; } BSL_SAL_FREE(msg->certTypes); #ifdef HITLS_TLS_PROTO_TLS13 BSL_SAL_FREE(msg->certificateReqCtx); BSL_SAL_FREE(msg->signatureAlgorithmsCert); #endif /* HITLS_TLS_PROTO_TLS13 */ return; } #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/parse/src/parse_certificate_request.c
C
unknown
15,841
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER) || defined(HITLS_TLS_PROTO_TLS13) #include "tls_binlog_id.h" #include "bsl_log.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "bsl_bytes.h" #include "crypt_algid.h" #include "hitls_error.h" #include "cert_method.h" #include "hs_msg.h" #include "hs_ctx.h" #include "hs_verify.h" #include "parse_msg.h" #include "parse_common.h" #include "config_type.h" static int32_t CheckSignHashAlg(TLS_Ctx *ctx, uint16_t signHashAlg) { int32_t ret = CheckPeerSignScheme(ctx, ctx->hsCtx->peerCert, signHashAlg); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(ctx, ret, 0, NULL, ALERT_ILLEGAL_PARAMETER); } TLS_Config *config = &ctx->config.tlsConfig; #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { const TLS_SigSchemeInfo *schemeInfo = ConfigGetSignatureSchemeInfo(config, signHashAlg); if (schemeInfo == NULL || ((schemeInfo->certVersionBits & TLS13_VERSION_BIT) == 0)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16195, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "not allowed to use 0x%X signAlg tls1.3.", signHashAlg, 0, 0, 0); return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORT_SIGN_ALG, 0, NULL, ALERT_HANDSHAKE_FAILURE); } } #endif /* HITLS_TLS_PROTO_TLS13 */ uint32_t i = 0; for (i = 0; i < config->signAlgorithmsSize; i++) { if (signHashAlg == config->signAlgorithms[i]) { break; } } if (i == config->signAlgorithmsSize) { return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORT_SIGN_ALG, BINLOG_ID15865, BINGLOG_STR("the signHashAlg match failed"), ALERT_HANDSHAKE_FAILURE); } #ifdef HITLS_TLS_FEATURE_SECURITY if (SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_SIGALG_CHECK, 0, signHashAlg, NULL) != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17159, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "signHashAlg 0x%x SslCheck fail", signHashAlg, 0, 0, 0); return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORT_SIGN_ALG, 0, NULL, ALERT_HANDSHAKE_FAILURE); } #endif return HITLS_SUCCESS; } static int32_t ParseCertificateVerifyPre(ParsePacket *pkt, uint16_t *signHashAlg) { const char *logStr = BINGLOG_STR("parse cert verifypre fail"); /* 2-byte signature hash algorithm + 2-byte signature data length. If the message length is less than 4 bytes, a failure message is returned. */ if (pkt->bufLen < 4u) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16964, logStr, ALERT_DECODE_ERROR); } if (pkt->ctx->negotiatedInfo.version >= HITLS_VERSION_TLS12) { int32_t ret = ParseBytesToUint16(pkt, signHashAlg); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16965, logStr, ALERT_DECODE_ERROR); } if (CheckSignHashAlg(pkt->ctx, *signHashAlg) != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_UNSUPPORT_SIGN_ALG); return HITLS_PARSE_UNSUPPORT_SIGN_ALG; } } return HITLS_SUCCESS; } static int32_t KeyMatchSignAlg(TLS_Ctx *ctx, HITLS_SignHashAlgo signScheme, HITLS_CERT_KeyType keyType, HITLS_CERT_Key *key) { (void)key; HITLS_CERT_KeyType certKeyType = SAL_CERT_SignScheme2CertKeyType(ctx, signScheme); if (certKeyType != keyType) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16197, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "signScheme not matche key, signScheme is 0x%X, certKeyType is %u, keyType is %u", signScheme, certKeyType, keyType, 0); return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORT_SIGN_ALG, 0, NULL, ALERT_ILLEGAL_PARAMETER); } /* check curve matches signature algorithm, only check ec key for tls1.3 */ if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 HITLS_Config *config = &ctx->config.tlsConfig; const TLS_SigSchemeInfo *schemeInfo = ConfigGetSignatureSchemeInfo(config, signScheme); if (schemeInfo == NULL) { return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORT_SIGN_ALG, 0, NULL, ALERT_ILLEGAL_PARAMETER); } if (schemeInfo->paraId == CRYPT_PKEY_PARAID_MAX) { return HITLS_SUCCESS; } int32_t paramId = CRYPT_PKEY_PARAID_MAX; int32_t ret = SAL_CERT_KeyCtrl(config, key, CERT_KEY_CTRL_GET_PARAM_ID, NULL, (void *)&paramId); if (ret != HITLS_SUCCESS || paramId != schemeInfo->paraId) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16198, BINGLOG_STR("paramId mismatch sigScheme"), ALERT_INTERNAL_ERROR); } #endif /* HITLS_TLS_PROTO_TLS13 */ return HITLS_SUCCESS; } static int VerifySignData(TLS_Ctx *ctx, uint16_t signHashAlg, const uint8_t *sign, uint16_t signSize) { CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; if (ctx->hsCtx == NULL || ctx->hsCtx->peerCert == NULL) { return ParseErrorProcess(ctx, HITLS_PARSE_VERIFY_SIGN_FAIL, BINLOG_ID15866, BINGLOG_STR("no peer certificate"), ALERT_CERTIFICATE_REQUIRED); } HITLS_CERT_X509 *cert = SAL_CERT_PairGetX509(ctx->hsCtx->peerCert); HITLS_CERT_Key *pubkey = NULL; int32_t ret = SAL_CERT_X509Ctrl(&ctx->config.tlsConfig, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16966, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GET_PUB_KEY fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } HITLS_SignHashAlgo signScheme = signHashAlg; HITLS_CERT_KeyType keyType = TLS_CERT_KEY_TYPE_UNKNOWN; ret = SAL_CERT_KeyCtrl(&ctx->config.tlsConfig, pubkey, CERT_KEY_CTRL_GET_TYPE, NULL, (void *)&keyType); if (ret != HITLS_SUCCESS) { SAL_CERT_KeyFree(mgrCtx, pubkey); return ParseErrorProcess(ctx, ret, BINLOG_ID16072, BINGLOG_STR("SAL_CERT_KeyCtrl fails"), ALERT_INTERNAL_ERROR); } if (signScheme == 0) { /** If the value of the signature hash algorithm is 0, the peer does not send the signature algorithm. In this case, we need to obtain the default signature algorithm through the certificate. */ signScheme = SAL_CERT_GetDefaultSignHashAlgo(keyType); if (signScheme == CERT_SIG_SCHEME_UNKNOWN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16073, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "no available signature scheme, key type = %u.", keyType, 0, 0, 0); SAL_CERT_KeyFree(mgrCtx, pubkey); return ParseErrorProcess(ctx, HITLS_PARSE_VERIFY_SIGN_FAIL, 0, NULL, ALERT_INTERNAL_ERROR); } } /* check whether the signature scheme matches the certificate key */ if (KeyMatchSignAlg(ctx, signScheme, keyType, pubkey) != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16967, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "KeyMatchSignAlg fail", 0, 0, 0, 0); SAL_CERT_KeyFree(mgrCtx, pubkey); return HITLS_PARSE_VERIFY_SIGN_FAIL; } /** verifying certificate data */ ret = VERIFY_VerifySignData(ctx, pubkey, signScheme, sign, signSize); SAL_CERT_KeyFree(mgrCtx, pubkey); return ret; } int32_t ParseCertificateVerify(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { uint16_t signHashAlg = 0; uint32_t offset = 0; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &offset}; int32_t ret = ParseCertificateVerifyPre(&pkt, &signHashAlg); if (ret != HITLS_SUCCESS) { return ret; } const char *logStr = BINGLOG_STR("parse cert verify fail"); uint16_t signSize = 0; ret = ParseBytesToUint16(&pkt, &signSize); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16968, logStr, ALERT_DECODE_ERROR); } if ((signSize != (pkt.bufLen - *pkt.bufOffset)) || (signSize == 0)) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16969, logStr, ALERT_DECODE_ERROR); } const uint8_t *sign = &pkt.buf[*pkt.bufOffset]; ret = VerifySignData(pkt.ctx, signHashAlg, sign, signSize); if (ret != HITLS_SUCCESS) { return ret; } CertificateVerifyMsg *msg = &hsMsg->body.certificateVerify; msg->signHashAlg = signHashAlg; msg->signSize = signSize; BSL_SAL_FREE(msg->sign); msg->sign = BSL_SAL_Dump(sign, signSize); if (msg->sign == NULL) { return ParseErrorProcess(pkt.ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID16970, BINGLOG_STR("Dump fail"), ALERT_INTERNAL_ERROR); } pkt.ctx->peerInfo.peerSignHashAlg = signHashAlg; return HITLS_SUCCESS; } void CleanCertificateVerify(CertificateVerifyMsg *msg) { if (msg == NULL) { return; } BSL_SAL_FREE(msg->sign); return; } #endif /* HITLS_TLS_HOST_CLIENT || HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/parse/src/parse_certificate_verify.c
C
unknown
9,669
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_config.h" #include "hs_msg.h" #include "hs.h" #include "parse_common.h" #include "parse_extensions.h" #include "parse_msg.h" #define SINGLE_CIPHER_SUITE_SIZE 2u /* Length of the signature cipher suite */ #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION static int32_t StoreClientCipherSuites(TLS_Ctx *ctx, ClientHelloMsg *msg) { uint32_t scsvCount = 0; scsvCount += msg->haveEmptyRenegoScsvCipher ? 1 : 0; scsvCount += msg->haveFallBackScsvCipher ? 1 : 0; if (scsvCount == msg->cipherSuitesSize) { BSL_SAL_FREE(ctx->peerInfo.cipherSuites); ctx->peerInfo.cipherSuitesSize = 0; return HITLS_SUCCESS; } uint32_t tmpSize = 0; BSL_SAL_FREE(ctx->peerInfo.cipherSuites); uint32_t peerCipherSuitesSize = ((uint32_t)msg->cipherSuitesSize - scsvCount) * sizeof(uint16_t); ctx->peerInfo.cipherSuites = (uint16_t *)BSL_SAL_Malloc(peerCipherSuitesSize); if (ctx->peerInfo.cipherSuites == NULL) { BSL_SAL_FREE(msg->cipherSuites); ctx->peerInfo.cipherSuitesSize = 0; return ParseErrorProcess(ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID16237, BINGLOG_STR("peer cipherSuites dump fail"), ALERT_UNKNOWN); } for (uint16_t index = 0u; index < msg->cipherSuitesSize; index++) { if (msg->cipherSuites[index] == TLS_EMPTY_RENEGOTIATION_INFO_SCSV || msg->cipherSuites[index] == TLS_FALLBACK_SCSV) { continue; } ctx->peerInfo.cipherSuites[tmpSize] = msg->cipherSuites[index]; tmpSize += 1; } ctx->peerInfo.cipherSuitesSize = (uint16_t)tmpSize; return HITLS_SUCCESS; } #endif /** * @brief Parse the cipher suite list of Client Hello messages. * * @param pkt [IN] parse context * @param msg [OUT] Client Hello Structure * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. */ static int32_t ParseClientHelloCipherSuites(ParsePacket *pkt, ClientHelloMsg *msg) { uint16_t cipherSuitesLen = 0; int32_t ret = ParseBytesToUint16(pkt, &cipherSuitesLen); const char *logStr = BINGLOG_STR("parse cipherSuites failed."); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15700, logStr, ALERT_DECODE_ERROR); } if (((uint32_t)cipherSuitesLen > (pkt->bufLen - *pkt->bufOffset)) || (cipherSuitesLen % SINGLE_CIPHER_SUITE_SIZE) != 0u) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15342, logStr, ALERT_DECODE_ERROR); } if (cipherSuitesLen == 0u) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15701, logStr, ALERT_ILLEGAL_PARAMETER); } msg->cipherSuitesSize = cipherSuitesLen / SINGLE_CIPHER_SUITE_SIZE; BSL_SAL_FREE(msg->cipherSuites); msg->cipherSuites = (uint16_t *)BSL_SAL_Malloc(((uint32_t)msg->cipherSuitesSize) * sizeof(uint16_t)); if (msg->cipherSuites == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15702, BINGLOG_STR("cipherSuites malloc fail"), ALERT_UNKNOWN); } /* Parse the cipher suite */ for (uint16_t index = 0u; index < msg->cipherSuitesSize; index++) { msg->cipherSuites[index] = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15703, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "got cipher suite from client:0x%x.", msg->cipherSuites[index], 0, 0, 0); if (msg->cipherSuites[index] == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { msg->haveEmptyRenegoScsvCipher = true; } if (msg->cipherSuites[index] == TLS_FALLBACK_SCSV) { msg->haveFallBackScsvCipher = true; } } #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION ret = StoreClientCipherSuites(pkt->ctx, msg); #endif return ret; } /** * @brief List of compression methods for parsing Client Hello messages * * @param pkt [IN] parse context * @param msg [OUT] Client Hello Structure * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. * @retval HITLS_MEMALLOC_FAIL Memory application failed. */ static int32_t ParseClientHelloCompressionMethods(ParsePacket *pkt, ClientHelloMsg *msg) { uint8_t compressionMethodsLen = 0; const char *logStr = BINGLOG_STR("parse compressionMethod failed."); int32_t ret = ParseBytesToUint8(pkt, &compressionMethodsLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15704, logStr, ALERT_DECODE_ERROR); } if ((compressionMethodsLen > (pkt->bufLen - *pkt->bufOffset)) || (compressionMethodsLen == 0u)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15705, logStr, ALERT_DECODE_ERROR); } ret = ParseBytesToArray(pkt, &msg->compressionMethods, compressionMethodsLen); if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID16146, BINGLOG_STR("compressionMethods malloc fail."), ALERT_UNKNOWN); } msg->compressionMethodsSize = compressionMethodsLen; for (uint32_t i = 0; i < compressionMethodsLen; i++) { if (msg->compressionMethods[i] == 0u) { return HITLS_SUCCESS; } } return ParseErrorProcess(pkt->ctx, HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD, BINLOG_ID16238, logStr, ALERT_DECODE_ERROR); } /** * @brief Parse the Client Hello extension messages. * * @param pkt [IN] parse context * @param msg [OUT] Client Hello Structure * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. * @retval HITLS_PARSE_DUPLICATE_EXTENSIVE_MSG Extended message */ static int32_t ParseClientHelloExtensions(ParsePacket *pkt, ClientHelloMsg *msg) { uint16_t exMsgLen = 0; const char *logStr = BINGLOG_STR("parse extension length failed."); int32_t ret = ParseBytesToUint16(pkt, &exMsgLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15707, logStr, ALERT_DECODE_ERROR); } if (exMsgLen != (pkt->bufLen - *pkt->bufOffset)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15708, logStr, ALERT_DECODE_ERROR); } if (exMsgLen == 0u) { return HITLS_SUCCESS; } return ParseClientExtension(pkt->ctx, &pkt->buf[*pkt->bufOffset], exMsgLen, msg); } int32_t ParseClientHello(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_Msg *hsMsg) { ClientHelloMsg *msg = &hsMsg->body.clientHello; uint32_t bufOffset = 0; ParsePacket pkt = {.ctx = ctx, .buf = data, .bufLen = len, .bufOffset = &bufOffset}; /* Parse the version number. The version number occupies two bytes */ int32_t ret = ParseVersion(&pkt, &msg->version); if (ret != HITLS_SUCCESS) { return ret; } ctx->negotiatedInfo.clientVersion = msg->version; /* Parse the random number. The random number occupies 32 bytes */ ret = ParseRandom(&pkt, msg->randomValue, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { return ret; } ret = ParseSessionId(&pkt, &msg->sessionIdSize, &msg->sessionId); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { /* Cookies need to be parsed in DTLS */ ret = ParseCookie(&pkt, &msg->cookieLen, &msg->cookie); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* Parse the cipher suite. After the parsing is complete, update the msg->cipherSuitesSize and msg->cipherSuites */ ret = ParseClientHelloCipherSuites(&pkt, msg); if (ret != HITLS_SUCCESS) { return ret; } /* Parse compression method */ ret = ParseClientHelloCompressionMethods(&pkt, msg); if (ret != HITLS_SUCCESS) { return ret; } if (len == bufOffset) { return HITLS_SUCCESS; } return ParseClientHelloExtensions(&pkt, msg); } void CleanClientHello(ClientHelloMsg *msg) { // The value of msg->refCnt is not 0, indicating that the ClientHelloMsg resource is hosted in the hrr scenario if (msg == NULL || msg->refCnt != 0) { return; } BSL_SAL_FREE(msg->sessionId); BSL_SAL_FREE(msg->cookie); BSL_SAL_FREE(msg->cipherSuites); BSL_SAL_FREE(msg->compressionMethods); BSL_SAL_FREE(msg->extensionBuff); CleanClientHelloExtension(msg); return; } #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/parse/src/parse_client_hello.c
C
unknown
9,663
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "hitls_crypt_type.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_common.h" #include "parse_msg.h" #include "parse_common.h" #ifdef HITLS_TLS_SUITE_KX_ECDHE /** * @brief Parse the client ecdh message. * * @param ctx [IN] TLS context * @param data [IN] message buffer * @param len [IN] message buffer length * @param hsMsg [OUT] Parsed message structure * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. */ static int32_t ParseClientKxMsgEcdhe(ParsePacket *pkt, ClientKeyExchangeMsg *msg) { const char *logStr = BINGLOG_STR("clientKeyEx length error."); /* Compatible with OpenSSL, add 3 bytes to the client key exchange */ #ifdef HITLS_TLS_PROTO_TLCP11 if (pkt->ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { // Curve type + Curve ID + Public key length uint8_t minLen = sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint8_t); if (pkt->bufLen - *pkt->bufOffset < minLen) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16222, logStr, ALERT_DECODE_ERROR); } // Ignore the three bytes *pkt->bufOffset += sizeof(uint8_t) + sizeof(uint16_t); } #endif uint8_t pubKeySize = 0; int32_t ret = ParseOneByteLengthField(pkt, &pubKeySize, &msg->data); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15635, logStr, ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15637, BINGLOG_STR("pubKey malloc fail."), ALERT_UNKNOWN); } if ((pkt->bufLen != *pkt->bufOffset) || (pubKeySize == 0)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15636, BINGLOG_STR("length of client ecdh pubKeySize is incorrect."), ALERT_DECODE_ERROR); } msg->dataSize = pubKeySize; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE /** * @brief Parse the Client Dhe message. * * @param ctx [IN] TLS context * @param data [IN] message buffer * @param len [IN] message buffer length * @param hsMsg [OUT] Parsed message structure * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. */ static int32_t ParseClientKxMsgDhe(ParsePacket *pkt, ClientKeyExchangeMsg *msg) { uint16_t pubKeySize = 0; int32_t ret = ParseTwoByteLengthField(pkt, &pubKeySize, &msg->data); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15638, BINGLOG_STR("clientKeyEx length error."), ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15640, BINGLOG_STR("pubKey malloc fail."), ALERT_UNKNOWN); } if ((pkt->bufLen != *pkt->bufOffset) || (pubKeySize == 0)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15639, BINGLOG_STR("length of client dh pubKeySize is incorrect."), ALERT_DECODE_ERROR); } msg->dataSize = (uint32_t)pubKeySize; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_DHE */ #if defined(HITLS_TLS_SUITE_KX_RSA) || defined(HITLS_TLS_PROTO_TLCP11) static int32_t ParseClientKxMsgRsa(ParsePacket *pkt, ClientKeyExchangeMsg *msg) { uint32_t encLen = pkt->bufLen - *pkt->bufOffset; const char *logStr = BINGLOG_STR("Parse RSA Premaster Secret error."); int32_t ret = 0; uint16_t parsedEncLen = 0; ret = ParseBytesToUint16(pkt, &parsedEncLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15641, logStr, ALERT_DECODE_ERROR); } encLen = parsedEncLen; if ((encLen != (pkt->bufLen - *pkt->bufOffset)) || (encLen == 0)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15642, logStr, ALERT_DECODE_ERROR); } ret = ParseBytesToArray(pkt, &msg->data, encLen); if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15643, BINGLOG_STR("pubKey malloc fail."), ALERT_UNKNOWN); } msg->dataSize = encLen; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_RSA || HITLS_TLS_PROTO_TLCP11 */ #ifdef HITLS_TLS_FEATURE_PSK static int32_t ParseClientKxMsgIdentity(ParsePacket *pkt, ClientKeyExchangeMsg *msg) { uint16_t identityLen = 0; int32_t ret = ParseBytesToUint16(pkt, &identityLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16972, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ParseBytesToUint16 fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } if ((identityLen > pkt->bufLen - *pkt->bufOffset) || (identityLen > HS_PSK_IDENTITY_MAX_LEN)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16973, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "identityLen err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } uint8_t *identity = NULL; if (identityLen != 0) { identity = (uint8_t *)BSL_SAL_Calloc(1u, (identityLen + 1) * sizeof(uint8_t)); if (identity == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16974, 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(identity, identityLen + 1, &pkt->buf[*pkt->bufOffset], identityLen); } msg->pskIdentity = identity; msg->pskIdentitySize = identityLen; *pkt->bufOffset += identityLen; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PSK */ int32_t ParseClientKeyExchange(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_Msg *hsMsg) { int32_t ret; uint32_t offset = 0u; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; ClientKeyExchangeMsg *msg = &hsMsg->body.clientKeyExchange; ParsePacket pkt = {.ctx = ctx, .buf = data, .bufLen = len, .bufOffset = &offset}; #ifdef HITLS_TLS_FEATURE_PSK if (IsPskNegotiation(ctx)) { ret = ParseClientKxMsgIdentity(&pkt, msg); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_PSK */ switch (hsCtx->kxCtx->keyExchAlgo) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: case HITLS_KEY_EXCH_ECDHE_PSK: ret = ParseClientKxMsgEcdhe(&pkt, msg); break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = ParseClientKxMsgDhe(&pkt, msg); break; #endif /* HITLS_TLS_SUITE_KX_DHE */ #if defined(HITLS_TLS_SUITE_KX_RSA) || defined(HITLS_TLS_PROTO_TLCP11) case HITLS_KEY_EXCH_RSA: case HITLS_KEY_EXCH_RSA_PSK: case HITLS_KEY_EXCH_ECC: ret = ParseClientKxMsgRsa(&pkt, msg); break; #endif /* HITLS_TLS_SUITE_KX_RSA || HITLS_TLS_PROTO_TLCP11 */ case HITLS_KEY_EXCH_PSK: return HITLS_SUCCESS; default: ret = HITLS_PARSE_UNSUPPORT_KX_ALG; break; } if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15644, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse client key exchange msg fail.", 0, 0, 0, 0); CleanClientKeyExchange(msg); } return ret; } void CleanClientKeyExchange(ClientKeyExchangeMsg *msg) { if (msg == NULL) { return; } #ifdef HITLS_TLS_FEATURE_PSK BSL_SAL_FREE(msg->pskIdentity); #endif /* HITLS_TLS_FEATURE_PSK */ BSL_SAL_FREE(msg->data); return; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/parse/src/parse_client_key_exchange.c
C
unknown
9,004
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #include "securec.h" #include "bsl_bytes.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "hs_ctx.h" #include "parse_common.h" int32_t ParseVersion(ParsePacket *pkt, uint16_t *version) { int32_t ret = ParseBytesToUint16(pkt, version); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15645, BINGLOG_STR("parse version failed"), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } int32_t ParseRandom(ParsePacket *pkt, uint8_t *random, uint32_t randomSize) { int32_t ret = ParseCopyBytesToArray(pkt, random, randomSize); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15646, BINGLOG_STR("parse random failed."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } int32_t ParseSessionId(ParsePacket *pkt, uint8_t *idSize, uint8_t **id) { int32_t ret = ParseOneByteLengthField(pkt, idSize, id); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15647, BINGLOG_STR("parse sessionId failed."), ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15651, BINGLOG_STR("sessionId malloc fail."), ALERT_UNKNOWN); } if (*idSize == 0u) { return HITLS_SUCCESS; } /* According to RFC 5246, the length of sessionId cannot exceed 32 bytes */ if (*idSize > TLS_HS_MAX_SESSION_ID_SIZE) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15649, BINGLOG_STR("sessionId length over 32."), ALERT_DECODE_ERROR); } /* The session ID length must be greater than or equal to 24 bytes according to the company security redline */ if (*idSize < TLS_HS_MIN_SESSION_ID_SIZE) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15650, BINGLOG_STR("sessionId length less than 24."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } int32_t ParseCookie(ParsePacket *pkt, uint8_t *cookieLen, uint8_t **cookie) { int32_t ret = ParseOneByteLengthField(pkt, cookieLen, cookie); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15652, BINGLOG_STR("parse cookie failed."), ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15654, BINGLOG_STR("cookie malloc failed."), ALERT_UNKNOWN); } return HITLS_SUCCESS; } int32_t ParseBytesToUint8(ParsePacket *pkt, uint8_t *object) { if (pkt->bufLen - *pkt->bufOffset < sizeof(uint8_t)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16975, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen err", 0, 0, 0, 0); return HITLS_PARSE_INVALID_MSG_LEN; } *object = (uint8_t)pkt->buf[*pkt->bufOffset]; *pkt->bufOffset += sizeof(uint8_t); return HITLS_SUCCESS; } int32_t ParseBytesToUint16(ParsePacket *pkt, uint16_t *object) { if (pkt->bufLen - *pkt->bufOffset < sizeof(uint16_t)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16976, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen err", 0, 0, 0, 0); return HITLS_PARSE_INVALID_MSG_LEN; } *object = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); return HITLS_SUCCESS; } int32_t ParseBytesToUint24(ParsePacket *pkt, uint32_t *object) { if (pkt->bufLen - *pkt->bufOffset < UINT24_SIZE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16977, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen err", 0, 0, 0, 0); return HITLS_PARSE_INVALID_MSG_LEN; } *object = BSL_ByteToUint24(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += UINT24_SIZE; return HITLS_SUCCESS; } int32_t ParseBytesToUint32(ParsePacket *pkt, uint32_t *object) { if (pkt->bufLen - *pkt->bufOffset < sizeof(uint32_t)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16978, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen err", 0, 0, 0, 0); return HITLS_PARSE_INVALID_MSG_LEN; } *object = BSL_ByteToUint32(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint32_t); return HITLS_SUCCESS; } int32_t ParseOneByteLengthField(ParsePacket *pkt, uint8_t *objectSize, uint8_t **object) { int32_t ret = ParseBytesToUint8(pkt, objectSize); if (ret != HITLS_SUCCESS) { return ret; } return ParseBytesToArray(pkt, object, *objectSize); } int32_t ParseTwoByteLengthField(ParsePacket *pkt, uint16_t *objectSize, uint8_t **object) { int32_t ret = ParseBytesToUint16(pkt, objectSize); if (ret != HITLS_SUCCESS) { return ret; } return ParseBytesToArray(pkt, object, *objectSize); } int32_t ParseBytesToArray(ParsePacket *pkt, uint8_t **object, uint32_t length) { BSL_SAL_FREE(*object); if (pkt->bufLen - *pkt->bufOffset < length) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16979, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen err", 0, 0, 0, 0); return HITLS_PARSE_INVALID_MSG_LEN; } if (length == 0) { return HITLS_SUCCESS; } *object = (uint8_t *)BSL_SAL_Malloc(length); if (*object == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16980, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Malloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(*object, length, &pkt->buf[*pkt->bufOffset], length); *pkt->bufOffset += length; return HITLS_SUCCESS; } int32_t ParseCopyBytesToArray(ParsePacket *pkt, uint8_t *object, uint32_t length) { if (pkt->bufLen - *pkt->bufOffset < length) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16981, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen err", 0, 0, 0, 0); return HITLS_PARSE_INVALID_MSG_LEN; } (void)memcpy_s(object, length, &pkt->buf[*pkt->bufOffset], length); *pkt->bufOffset += length; return HITLS_SUCCESS; } int32_t ParseErrorProcess(TLS_Ctx *ctx, int32_t err, uint32_t logId, const void *format, ALERT_Description description) { BSL_ERR_PUSH_ERROR(err); if (format != NULL) { BSL_LOG_BINLOG_FIXLEN(logId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, format, 0, 0, 0, 0); } if (description != ALERT_UNKNOWN) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, description); } return err; } int32_t CheckPeerSignScheme(HITLS_Ctx *ctx, CERT_Pair *peerCert, uint16_t signScheme) { if (peerCert == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_PARSE_UNSUPPORT_SIGN_ALG, BINLOG_ID17160, "peerCert null"); } HITLS_Config *config = &ctx->config.tlsConfig; HITLS_CERT_Key *pubkey = NULL; int32_t ret = SAL_CERT_X509Ctrl(config, peerCert->cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17140, "get pubkey fail"); } uint32_t keyType = TLS_CERT_KEY_TYPE_UNKNOWN; ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_TYPE, NULL, (void *)&keyType); SAL_CERT_KeyFree(config->certMgrCtx, pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17099, "get pubkey type fail"); } if (keyType != SAL_CERT_SignScheme2CertKeyType(ctx, signScheme)) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_PARSE_UNSUPPORT_SIGN_ALG, BINLOG_ID17156, "signScheme err"); } return HITLS_SUCCESS; }
2301_79861745/bench_create
tls/handshake/parse/src/parse_common.c
C
unknown
8,245
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef PARSER_COMMON_H #define PARSER_COMMON_H #include <stdint.h> #include "tls.h" #include "hs_msg.h" #include "cert_method.h" #include "cert_mgr_ctx.h" #include "security.h" #ifdef __cplusplus extern "C" { #endif typedef struct { TLS_Ctx *ctx; const uint8_t *buf; uint32_t bufLen; uint32_t *bufOffset; } ParsePacket; /** * @brief Parse the version of the message * * @param pkt [IN] Context for parsing * @param version [OUT] Parsed version * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseVersion(ParsePacket *pkt, uint16_t *version); /** * @brief Parse random number in message * * @param pkt [IN] Context for parsing * @param random [OUT] Parsed random number * @param randomSize [IN] Random number length * * @retval HITLS_SUCCESS * @retval HITLS_MEMCPY_FAIL Memory Copy Failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseRandom(ParsePacket *pkt, uint8_t *random, uint32_t randomSize); /** * @brief Parse SessionId in message * * @param pkt [IN] Context for parsing * @param id [OUT] Parsed session ID * @param idSize [OUT] Parsed session ID length * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocation failed * @retval HITLS_MEMCPY_FAIL Memory Copy Failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseSessionId(ParsePacket *pkt, uint8_t *idSize, uint8_t **id); /** * @brief Parse Cookie in message * * @param pkt [IN] Context for parsing * @param cookie [OUT] Parsed cookie * @param cookieLen [OUT] Parsed cookie length * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocation failed * @retval HITLS_MEMCPY_FAIL Memory Copy Failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseCookie(ParsePacket *pkt, uint8_t *cookieLen, uint8_t **cookie); /** * @brief Parse TrustCA list in message * * @param data [IN] TrustCAList message buffer * @param buf [IN] TrustCAList message buffer length * * @retval HITLS_TrustedCAList * Pointer to the CAList header */ HITLS_TrustedCAList *ParseDNList(const uint8_t *data, uint32_t len); /** * @brief Free the buffer of TrustCAList * * @param listHead [IN] Pointer to the CAList header * * @retval void */ void FreeDNList(HITLS_TrustedCAList *caList); /** * @brief Parse uint8_t data * * @param pkt [IN] Context for parsing * @param object [OUT] Parsed data * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseBytesToUint8(ParsePacket *pkt, uint8_t *object); /** * @brief Parse uint16_t data * * @param pkt [IN] Context for parsing * @param object [OUT] Parsed data * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseBytesToUint16(ParsePacket *pkt, uint16_t *object); /** * @brief Parse 3 bytes data * * @param pkt [IN] Context for parsing * @param object [OUT] Parsed data * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseBytesToUint24(ParsePacket *pkt, uint32_t *object); /** * @brief Parse uint32_t data * * @param pkt [IN] Context for parsing * @param object [OUT] Parsed data * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseBytesToUint32(ParsePacket *pkt, uint32_t *object); /** * @brief Parse one byte length field, then parse the following content * * @param pkt [IN] Context for parsing * @param objectSize [OUT] Parsed one byte data length * @param object [OUT] Parsed data * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseOneByteLengthField(ParsePacket *pkt, uint8_t *objectSize, uint8_t **object); /** * @brief Parse two byte length field, then parse the following content * * @param pkt [IN] Context for parsing * @param objectSize [OUT] Parsed one byte data length * @param object [OUT] Parsed data * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseTwoByteLengthField(ParsePacket *pkt, uint16_t *objectSize, uint8_t **object); /** * @brief Parse data by length * * @param pkt [IN] Context for parsing * @param object [OUT] Parsed data, need memory allocation * @param length [IN] Length of data need be parsed * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseBytesToArray(ParsePacket *pkt, uint8_t **object, uint32_t length); /** * @brief Parse data by length * * @param pkt [IN] Context for parsing * @param object [OUT] Parsed data, do not need memory allocation * @param length [IN] Length of data need be parsed * * @retval HITLS_SUCCESS success * @retval HITLS_PARSE_INVALID_MSG_LEN bufLen is not enough */ int32_t ParseCopyBytesToArray(ParsePacket *pkt, uint8_t *object, uint32_t length); /** * @brief Error processing function in parse module * * @param ctx [IN] TLS context * @param err [IN] Error code need to be pushed and returned * @param logId [IN] binlogid * @param format [IN] Message for log function * @param description [IN] Alert description * @retval error code */ int32_t ParseErrorProcess(TLS_Ctx *ctx, int32_t err, uint32_t logId, const void *format, ALERT_Description description); /** * @brief Check whether the peer certificate matches the peer signature algorithm. * * @param ctx [IN] TLS context * @param peerCert [IN] peerCert * @param signScheme [IN] peer signScheme * @retval error code */ int32_t CheckPeerSignScheme(HITLS_Ctx *ctx, CERT_Pair *peerCert, uint16_t signScheme); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end PARSER_COMMON_H */
2301_79861745/bench_create
tls/handshake/parse/src/parse_common.h
C
unknown
6,553
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_TLS_HOST_CLIENT) && defined(HITLS_TLS_PROTO_TLS13) #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "tls.h" #include "rec.h" #include "hs.h" #include "hs_extensions.h" #include "hs_common.h" #include "parse_extensions.h" #include "parse_common.h" #include "custom_extensions.h" /** * @brief Release the memory in the message structure. * * @param msg [IN] message structure */ void CleanEncryptedExtensions(EncryptedExtensions *msg) { if (msg == NULL) { return; } BSL_SAL_FREE(msg->supportedGroups); #ifdef HITLS_TLS_FEATURE_ALPN BSL_SAL_FREE(msg->alpnSelected); #endif /* HITLS_TLS_FEATURE_ALPN */ return; } static int32_t ParseEncryptedSupportGroups(ParsePacket *pkt, EncryptedExtensions *msg) { /* Has parsed extensions of the same type */ if (msg->haveSupportedGroups == true) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_DUPLICATE_EXTENDED_MSG, BINLOG_ID15709, BINGLOG_STR("ClientSupportGroups repeated"), ALERT_ILLEGAL_PARAMETER); } uint16_t groupLen = 0; const char *logStr = BINGLOG_STR("parse supported groups len fail."); int32_t ret = ParseBytesToUint16(pkt, &groupLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15710, logStr, ALERT_DECODE_ERROR); } groupLen /= sizeof(uint16_t); /* If the length of the message does not match the extended length, or the length is 0, the handshake message error is returned */ if (((groupLen * sizeof(uint16_t)) != (pkt->bufLen - sizeof(uint16_t))) || (groupLen == 0)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15711, logStr, ALERT_DECODE_ERROR); } BSL_SAL_FREE(msg->supportedGroups); msg->supportedGroups = (uint16_t *)BSL_SAL_Malloc(groupLen * sizeof(uint16_t)); if (msg->supportedGroups == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15712, BINGLOG_STR("supportedGroups malloc fail"), ALERT_UNKNOWN); } for (uint32_t i = 0; i < groupLen; i++) { msg->supportedGroups[i] = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); } msg->supportedGroupsSize = groupLen; msg->haveSupportedGroups = true; return HITLS_SUCCESS; } static int32_t ParseEncryptedExBody(TLS_Ctx *ctx, uint16_t extMsgType, const uint8_t *buf, uint32_t extMsgLen, EncryptedExtensions *msg) { uint32_t bufOffset = 0u; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = extMsgLen, .bufOffset = &bufOffset}; switch (extMsgType) { case HS_EX_TYPE_SUPPORTED_GROUPS: return ParseEncryptedSupportGroups(&pkt, msg); case HS_EX_TYPE_EARLY_DATA: return ParseEmptyExtension(ctx, HS_EX_TYPE_EARLY_DATA, extMsgLen, &msg->haveEarlyData); case HS_EX_TYPE_SERVER_NAME: return ParseEmptyExtension(ctx, HS_EX_TYPE_SERVER_NAME, extMsgLen, &msg->haveServerName); case HS_EX_TYPE_SIGNATURE_ALGORITHMS: case HS_EX_TYPE_KEY_SHARE: case HS_EX_TYPE_PRE_SHARED_KEY: case HS_EX_TYPE_STATUS_REQUEST: case HS_EX_TYPE_STATUS_REQUEST_V2: case HS_EX_TYPE_PSK_KEY_EXCHANGE_MODES: case HS_EX_TYPE_COOKIE: case HS_EX_TYPE_SUPPORTED_VERSIONS: case HS_EX_TYPE_CERTIFICATE_AUTHORITIES: case HS_EX_TYPE_POST_HS_AUTH: case HS_EX_TYPE_SIGNATURE_ALGORITHMS_CERT: return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORTED_EXTENSION, BINLOG_ID16239, BINGLOG_STR("Illegal extension received"), ALERT_ILLEGAL_PARAMETER); #ifdef HITLS_TLS_FEATURE_ALPN case HS_EX_TYPE_APP_LAYER_PROTOCOLS: return ParseServerSelectedAlpnProtocol( &pkt, &msg->haveSelectedAlpn, &msg->alpnSelected, &msg->alpnSelectedSize); #endif /* HITLS_TLS_FEATURE_ALPN */ default: break; } #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS)) { return ParseCustomExtensions(pkt.ctx, pkt.buf + *pkt.bufOffset, extMsgType, extMsgLen, HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS, NULL, 0); } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ return ParseErrorProcess(ctx, HITLS_PARSE_UNSUPPORTED_EXTENSION, BINLOG_ID16982, "unknow extension received", ALERT_UNSUPPORTED_EXTENSION); } // Parse the EncryptedExtensions extension message int32_t ParseEncryptedEx(TLS_Ctx *ctx, EncryptedExtensions *msg, const uint8_t *buf, uint32_t bufLen) { uint32_t bufOffset = 0u; int32_t ret; while (bufOffset < bufLen) { uint32_t extMsgLen = 0u; uint16_t extMsgType = HS_EX_TYPE_END; ret = ParseExHeader(ctx, &buf[bufOffset], bufLen - bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += HS_EX_HEADER_LEN; uint32_t extensionId = HS_GetExtensionTypeId(extMsgType); ret = CheckForDuplicateExtension(msg->extensionTypeMask, extensionId, ctx); if (ret != HITLS_SUCCESS) { return ret; } if (extensionId != HS_EX_TYPE_ID_UNRECOGNIZED #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION || !IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS) #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ ) { msg->extensionTypeMask |= 1ULL << extensionId; /* check whether the extension that is not sent is received. */ if (!GetExtensionFlagValue(ctx, extensionId)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17329, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get extension type %u.", extensionId, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } } ret = ParseEncryptedExBody(ctx, extMsgType, &buf[bufOffset], extMsgLen, msg); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += extMsgLen; } if (bufOffset != bufLen) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16239, BINGLOG_STR("encrypted extensions len incorrect"), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } // Parse the EncryptedExtensions message. int32_t ParseEncryptedExtensions(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { if ((buf == NULL) || (hsMsg == NULL)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16983, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } /* Parse the EncryptedExtensions extension message */ EncryptedExtensions *msg = &hsMsg->body.encryptedExtensions; uint32_t bufOffset = 0u; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &bufOffset}; /* Obtain the extended message length */ uint16_t exMsgLen = 0; const char *logStr = BINGLOG_STR("parse encrypted Extensions len fail."); int32_t ret = ParseBytesToUint16(&pkt, &exMsgLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16128, logStr, ALERT_DECODE_ERROR); } if (pkt.bufLen - *pkt.bufOffset != exMsgLen) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15715, logStr, ALERT_DECODE_ERROR); } return ParseEncryptedEx(pkt.ctx, msg, &pkt.buf[*pkt.bufOffset], exMsgLen); } #endif /* HITLS_TLS_HOST_CLIENT && HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/parse/src/parse_encrypted_extensions.c
C
unknown
8,601
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "tls.h" #include "hs.h" #include "hs_ctx.h" #include "hs_extensions.h" #include "parse_common.h" #include "parse_extensions.h" // Parse an empty extended message. int32_t ParseEmptyExtension(TLS_Ctx *ctx, uint16_t extMsgType, uint32_t extMsgLen, bool *haveExtension) { /* Parsed extensions of the same type */ if (*haveExtension) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15120, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "extension message type:%d len:%lu in hello message is repeated.", extMsgType, extMsgLen, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_PARSE_DUPLICATE_EXTENDED_MSG); return HITLS_PARSE_DUPLICATE_EXTENDED_MSG; } /* Parse the empty extended message */ if (extMsgLen != 0u) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15121, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "extension message type:%d len:%lu in hello message is nonzero.", extMsgType, extMsgLen, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); return HITLS_PARSE_INVALID_MSG_LEN; } *haveExtension = true; return HITLS_SUCCESS; } int32_t ParseExCookie(const uint8_t *buf, uint32_t bufLen, uint8_t **cookie, uint16_t *cookieLen) { *cookie = NULL; // Initialize the function entry to prevent wild pointers uint32_t bufOffset = 0; if (bufLen < sizeof(uint16_t)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17007, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen error", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); return HITLS_PARSE_INVALID_MSG_LEN; } /* Extract the cookie length */ uint32_t tmpCookieLen = BSL_ByteToUint16(&buf[bufOffset]); bufOffset += sizeof(uint16_t); /* If the cookie length is incorrect, an error code is returned */ if (tmpCookieLen != (bufLen - bufOffset) || tmpCookieLen == 0u) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17008, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen error", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); return HITLS_PARSE_INVALID_MSG_LEN; } /* Obtain the cookie */ uint8_t *tmpCookie = BSL_SAL_Dump(&buf[bufOffset], tmpCookieLen); if (tmpCookie == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15161, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cookie malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } *cookie = tmpCookie; *cookieLen = (uint16_t)tmpCookieLen; return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t ParseSecRenegoInfo(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, uint8_t **secRenegoInfo, uint8_t *secRenegoInfoSize) { /* The message length is not enough to parse secRenegoInfo */ if (bufLen < sizeof(uint8_t)) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15184, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "extension message length (renegotiation info) in client hello message is incorrect.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } /* Parse the length of secRenegoInfo */ uint32_t bufOffset = 0; uint8_t tmpSize = buf[bufOffset]; bufOffset++; if (tmpSize != (bufLen - bufOffset)) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15185, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the renegotiation info size in the hello messag is incorrect.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } if (tmpSize == 0) { return HITLS_SUCCESS; } /* Parse secRenegoInfo */ uint8_t *tmpInfo = (uint8_t *)BSL_SAL_Dump(&buf[bufOffset], tmpSize); if (tmpInfo == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15186, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "secRenegoInfo malloc fail when parse renegotiation info.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } *secRenegoInfo = tmpInfo; *secRenegoInfoSize = tmpSize; return HITLS_SUCCESS; } #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ /** * @brief Parse the extended message type and length. * * @param ctx [IN] TLS context * @param buf [IN] message buffer, starting from the extension type. * @param bufLen [IN] Packet length * @param extMsgType [OUT] Extended message type * @param extMsgLen [OUT] Extended message length * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_PARSE_DUPLICATE_EXTENSIVE_MSG Extended message */ int32_t ParseExHeader(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, uint16_t *extMsgType, uint32_t *extMsgLen) { if (bufLen < HS_EX_HEADER_LEN) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15189, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the extension len of client hello msg is incorrect", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } uint32_t bufOffset = 0u; uint16_t type = 0u; uint32_t len = 0u; /* Obtain the message type */ type = BSL_ByteToUint16(&buf[bufOffset]); bufOffset += sizeof(uint16_t); /* Obtain the message length */ len = BSL_ByteToUint16(&buf[bufOffset]); bufOffset += sizeof(uint16_t); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15190, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "get extension message in hello, type:%d len:%lu.", type, len, 0, 0); if (len > (bufLen - bufOffset)) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15191, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "extension message type:%d len:%lu in hello message is incorrect.", type, len, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } /* Update the extended message type and length */ *extMsgType = type; *extMsgLen = len; return HITLS_SUCCESS; } int32_t ParseDupExtProcess(TLS_Ctx *ctx, uint32_t logId, const void *format) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_DUPLICATE_EXTENDED_MSG); if (format != NULL) { BSL_LOG_BINLOG_VARLEN(logId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "extension type %s is repeated.", format); } ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_PARSE_DUPLICATE_EXTENDED_MSG; } int32_t ParseErrorExtLengthProcess(TLS_Ctx *ctx, uint32_t logId, const void *format) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); if (format != NULL) { BSL_LOG_BINLOG_VARLEN(logId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "%s extension message length is incorrect", format); } ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } bool GetExtensionFlagValue(TLS_Ctx *ctx, uint32_t hsExTypeId) { switch (hsExTypeId) { case HS_EX_TYPE_ID_SERVER_NAME: return ctx->hsCtx->extFlag.haveServerName; case HS_EX_TYPE_ID_SUPPORTED_GROUPS: return ctx->hsCtx->extFlag.haveSupportedGroups; case HS_EX_TYPE_ID_POINT_FORMATS: return ctx->hsCtx->extFlag.havePointFormats; case HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS: return ctx->hsCtx->extFlag.haveSignatureAlgorithms; case HS_EX_TYPE_ID_EXTENDED_MASTER_SECRET: return ctx->hsCtx->extFlag.haveExtendedMasterSecret; case HS_EX_TYPE_ID_SUPPORTED_VERSIONS: return ctx->hsCtx->extFlag.haveSupportedVers; case HS_EX_TYPE_ID_CERTIFICATE_AUTHORITIES: return ctx->hsCtx->extFlag.haveCA; case HS_EX_TYPE_ID_POST_HS_AUTH: return ctx->hsCtx->extFlag.havePostHsAuth; case HS_EX_TYPE_ID_KEY_SHARE: return ctx->hsCtx->extFlag.haveKeyShare; case HS_EX_TYPE_ID_EARLY_DATA: return ctx->hsCtx->extFlag.haveEarlyData; case HS_EX_TYPE_ID_PSK_KEY_EXCHANGE_MODES: return ctx->hsCtx->extFlag.havePskExMode; case HS_EX_TYPE_ID_PRE_SHARED_KEY: return ctx->hsCtx->extFlag.havePreShareKey; case HS_EX_TYPE_ID_APP_LAYER_PROTOCOLS: return ctx->hsCtx->extFlag.haveAlpn; case HS_EX_TYPE_ID_SESSION_TICKET: return ctx->hsCtx->extFlag.haveTicket; case HS_EX_TYPE_ID_ENCRYPT_THEN_MAC: return ctx->hsCtx->extFlag.haveEncryptThenMac; case HS_EX_TYPE_ID_SIGNATURE_ALGORITHMS_CERT: return ctx->hsCtx->extFlag.haveSignatureAlgorithmsCert; case HS_EX_TYPE_ID_COOKIE: case HS_EX_TYPE_ID_RENEGOTIATION_INFO: default: break; } return true; } int32_t CheckForDuplicateExtension(uint64_t extensionTypeMask, uint32_t extensionId, TLS_Ctx *ctx) { // can not process duplication unknown ext, unknown ext is verified elsewhere if (((extensionTypeMask & (1ULL << extensionId)) != 0) && extensionId != HS_EX_TYPE_ID_UNRECOGNIZED) { BSL_ERR_PUSH_ERROR(HITLS_PARSE_DUPLICATE_EXTENDED_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17328, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "extension type %u is repeated.", extensionId, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_PARSE_DUPLICATE_EXTENDED_MSG; } return HITLS_SUCCESS; }
2301_79861745/bench_create
tls/handshake/parse/src/parse_extensions.c
C
unknown
10,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. */ #ifndef PARSE_EXTENSIONS_H #define PARSE_EXTENSIONS_H #include <stdint.h> #include "tls.h" #include "hs_msg.h" #include "parse_common.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Parse Client Hello extension * * @attention The input parameter pointer can't be NULL * If parsing fails, the invoker releases the allocated memory * * @param ctx [IN] TLS context * @param buf [IN] Message buffer, starting from the extension type * @param bufLen [IN] Message length * @param msg [OUT] Parsed message * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_MEMALLOC_FAIL Memory allocation failed * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG Extension duplicated */ int32_t ParseClientExtension(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, ClientHelloMsg *msg); /** * @brief Release the buffer in the Client Hello extension structure * * @param msg [IN] Message structure */ void CleanClientHelloExtension(ClientHelloMsg *msg); /** * @brief Parse server hello extension * * @attention The input parameter pointer can't be NULL * If the parsing fails, the invoker releases the allocated memory * * @param ctx [IN] TLS context * @param buf [IN] Message buffer, starting from the extension type * @param bufLen [IN] Message length * @param msg [OUT] Parsed message * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_MEMALLOC_FAIL Memory allocation failed * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG Extension duplicated * @retval HITLS_PARSE_UNSUPPORTED_EXTENSION Unsupported extension */ int32_t ParseServerExtension(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, ServerHelloMsg *msg); /** * @brief Parse extension type and length * * @param ctx [IN] TLS context * @param buf [IN] Message buffer, starting from the extension type * @param bufLen [IN] Message length * @param extMsgType [OUT] Extension type * @param extMsgLen [OUT] Extension length * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_MEMALLOC_FAIL Memory allocation failed * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG Extension duplicated */ int32_t ParseExHeader(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, uint16_t *extMsgType, uint32_t *extMsgLen); /** * @brief Release the buffer in the Server Hello extension structure * * @param msg [IN] Message structure */ void CleanServerHelloExtension(ServerHelloMsg *msg); /** * @brief Parse empty extension * * @param ctx [IN] TLS context * @param extMsgType [IN] Extension type * @param extMsgLen [IN] Extension length * @param haveExtension [OUT] Indicates whether there are extensions * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG Extension duplicated */ int32_t ParseEmptyExtension(TLS_Ctx *ctx, uint16_t extMsgType, uint32_t extMsgLen, bool *haveExtension); int32_t ParseExCookie(const uint8_t *buf, uint32_t bufLen, uint8_t **cookie, uint16_t *cookieLen); int32_t ParseSecRenegoInfo(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, uint8_t **secRenegoInfo, uint8_t *secRenegoInfoSize); int32_t ParseServerSelectedAlpnProtocol( ParsePacket *pkt, bool *haveSelectedAlpn, uint8_t **alpnSelected, uint16_t *alpnSelectedSize); /** * @brief Error process in duplicated extension * * @param ctx [IN] TLS context * @param logId [IN] binlogid * @param format [IN] Message for log function * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG */ int32_t ParseDupExtProcess(TLS_Ctx *ctx, uint32_t logId, const void *format); /** * @brief Parse extension length error * * @param ctx [IN] TLS context * @param logId [IN] binlogid * @param format [IN] Message for log function * @retval HITLS_PARSE_INVALID_MSG_LEN */ int32_t ParseErrorExtLengthProcess(TLS_Ctx *ctx, uint32_t logId, const void *format); bool GetExtensionFlagValue(TLS_Ctx *ctx, uint32_t hsExTypeId); int32_t CheckForDuplicateExtension(uint64_t extensionTypeMask, uint32_t extensionId, TLS_Ctx *ctx); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end PARSE_EXTENSIONS_H */
2301_79861745/bench_create
tls/handshake/parse/src/parse_extensions.h
C
unknown
4,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 "hitls_build.h" #ifdef HITLS_TLS_HOST_CLIENT #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "bsl_list.h" #include "hs_ctx.h" #include "hitls_error.h" #include "hitls_cert_type.h" #include "tls.h" #include "hs.h" #include "hs_extensions.h" #include "hs_common.h" #include "rec.h" #include "parse_common.h" #include "parse_extensions.h" #include "custom_extensions.h" // Parses the point format message sent by the server static int32_t ParseServerPointFormats(ParsePacket *pkt, ServerHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->havePointFormats == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15193, BINGLOG_STR("ServerPointFormats")); } uint8_t pointFormatsSize = 0; int32_t ret = ParseOneByteLengthField(pkt, &pointFormatsSize, &msg->pointFormats); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15194, BINGLOG_STR("ServerPointFormats")); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15196, BINGLOG_STR("pointFormats malloc fail."), ALERT_UNKNOWN); } if ((pkt->bufLen != *pkt->bufOffset) || (pointFormatsSize == 0u)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15195, BINGLOG_STR("ServerPointFormats")); } msg->havePointFormats = true; msg->pointFormatsSize = pointFormatsSize; return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 static int32_t ParseServerPreShareKey(ParsePacket *pkt, ServerHelloMsg *msg) { if (msg->haveSelectedIdentity == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15156, BINGLOG_STR("pre_shared_key")); } int32_t ret = ParseBytesToUint16(pkt, &msg->selectedIdentity); if (ret != HITLS_SUCCESS || pkt->bufLen != *pkt->bufOffset) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15157, BINGLOG_STR("pre_shared_key")); } msg->haveSelectedIdentity = true; return HITLS_SUCCESS; } int32_t ParseServerKeyShare(ParsePacket *pkt, ServerHelloMsg *msg) { if (msg->haveKeyShare == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15158, BINGLOG_STR("ServerKeyShare")); } int32_t ret = ParseBytesToUint16(pkt, &msg->keyShare.group); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15159, BINGLOG_STR("ServerKeyShare")); } if (pkt->bufLen == *pkt->bufOffset) { msg->haveKeyShare = true; return HITLS_SUCCESS; // If there is no subsequent content, the extension is the keyshare of hrr } uint16_t keyExchangeSize = 0; ret = ParseTwoByteLengthField(pkt, &keyExchangeSize, &msg->keyShare.keyExchange); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID16202, BINGLOG_STR("ServerKeyShare")); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID16984, BINGLOG_STR("ServerKeyShare"), ALERT_INTERNAL_ERROR); } if ((pkt->bufLen != *pkt->bufOffset) || (keyExchangeSize == 0u)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15160, BINGLOG_STR("ServerKeyShare")); } msg->keyShare.keyExchangeSize = keyExchangeSize; msg->haveKeyShare = true; return HITLS_SUCCESS; } int32_t ParseServerCookie(ParsePacket *pkt, ServerHelloMsg *msg) { if (msg->haveCookie == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15162, BINGLOG_STR("cookie")); } int32_t ret = ParseExCookie(pkt->buf, pkt->bufLen, &msg->cookie, &msg->cookieLen); if (ret != HITLS_SUCCESS) { return ret; } msg->haveCookie = true; return HITLS_SUCCESS; } // Parse the SupportedVersions message. static int32_t ParseServerSupportedVersions(ParsePacket *pkt, ServerHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->haveSupportedVersion == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15164, BINGLOG_STR("ServerSupportedVersions")); } int32_t ret = ParseBytesToUint16(pkt, &msg->supportedVersion); if (ret != HITLS_SUCCESS || pkt->bufLen != *pkt->bufOffset) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16985, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ParseBytesToUint16 fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); return HITLS_PARSE_INVALID_MSG_LEN; } msg->haveSupportedVersion = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ // Parses the extended master secret sent by the serve static int32_t ParseServerExtMasterSecret(ParsePacket *pkt, ServerHelloMsg *msg) { /* Parse the empty extended message */ return ParseEmptyExtension(pkt->ctx, HS_EX_TYPE_EXTENDED_MASTER_SECRET, pkt->bufLen, &msg->haveExtendedMasterSecret); } #ifdef HITLS_TLS_FEATURE_ALPN int32_t ParseServerSelectedAlpnProtocol( ParsePacket *pkt, bool *haveSelectedAlpn, uint8_t **alpnSelected, uint16_t *alpnSelectedSize) { /* Parsed extensions of the same type */ if (*haveSelectedAlpn == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15197, BINGLOG_STR("selected alpn protocol")); } uint16_t selectedAlpnListLen = 0; uint8_t selectedAlpnLen = 0; int32_t ret = ParseBytesToUint16(pkt, &selectedAlpnListLen); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15198, BINGLOG_STR("alpn")); } uint32_t offset = *pkt->bufOffset; ret = ParseBytesToUint8(pkt, &selectedAlpnLen); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID16253, BINGLOG_STR("alpn")); } /* If the length of the packet does not match the extended length, or the length is 0, the handshake message error * is returned */ if (((selectedAlpnListLen * sizeof(uint8_t)) != (pkt->bufLen - sizeof(uint16_t))) || (selectedAlpnListLen == 0)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15199, BINGLOG_STR("alpn")); } /* According to the protocol rfc7301, The alpn extension returned by s end is allowed to contain only one protocol * name, and returns a handshake message error */ /* Check whether the listsize of the alpn list returned by the server is anpn size + sizeof(uint8_t) */ if (selectedAlpnLen != selectedAlpnListLen - sizeof(uint8_t)) { return ParseErrorProcess(pkt->ctx, HITLS_MSG_HANDLE_ALPN_UNRECOGNIZED, BINLOG_ID16121, BINGLOG_STR("the number of Protocol in ALPN extensions is incorrect."), ALERT_DECODE_ERROR); } /* The length of bufLen meets: alpnLen | alpn | 0 */ *alpnSelected = (uint8_t *)BSL_SAL_Calloc(selectedAlpnLen + 1, sizeof(uint8_t)); if (*alpnSelected == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15200, BINGLOG_STR("selected alpn proto malloc fail."), ALERT_UNKNOWN); } (void)memcpy_s(*alpnSelected, selectedAlpnLen + 1, &pkt->buf[offset], selectedAlpnLen + 1); *alpnSelectedSize = selectedAlpnLen + 1; *haveSelectedAlpn = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_FEATURE_SNI /** * @brief server hello ServerName extension item * * @param ctx [IN] TLS context * @param buf [IN] message buffer * @param bufLen [IN] message length * @param msg [OUT] Parsed message * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_PARSE_DUPLICATE_EXTENSIVE_MSG Extended message */ static int32_t ParseServerServerName(ParsePacket *pkt, ServerHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->haveServerName == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15202, BINGLOG_STR("ServerName")); } /* If the message length is incorrect, an error code is returned */ /* rfc6066 * When the server decides to receive server_name, the server should include an extension of type "server_name" in * the (extended) server hello. The'extension_data' field for this extension should be empty */ if (pkt->bufLen != 0) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15203, BINGLOG_STR("ServerName")); } msg->haveServerName = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SNI */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t ParseServerSecRenegoInfo(ParsePacket *pkt, ServerHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->haveSecRenego == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15204, BINGLOG_STR("renegotiation info")); } uint8_t secRenegoInfoSize = 0; uint8_t *secRenegoInfo = NULL; int32_t ret = ParseSecRenegoInfo(pkt->ctx, pkt->buf, pkt->bufLen, &secRenegoInfo, &secRenegoInfoSize); if (ret != HITLS_SUCCESS) { return ret; } msg->secRenegoInfo = secRenegoInfo; msg->secRenegoInfoSize = secRenegoInfoSize; msg->haveSecRenego = true; return HITLS_SUCCESS; } #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET static int32_t ParseServerTicket(ParsePacket *pkt, ServerHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->haveTicket == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15964, BINGLOG_STR("ticket")); } /* The ticket extended data length of server hello can only be empty */ if (pkt->bufLen != 0) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15965, BINGLOG_STR("tiket")); } msg->haveTicket = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_ETM static int32_t ParseServerEncryptThenMac(ParsePacket *pkt, ServerHelloMsg *msg) { return ParseEmptyExtension(pkt->ctx, HS_EX_TYPE_ENCRYPT_THEN_MAC, pkt->bufLen, &msg->haveEncryptThenMac); } #endif /* HITLS_TLS_FEATURE_ETM */ /** * @brief Parses the extended message from server * * @param ctx [IN] TLS context * @param extMsgType [IN] Extended message type * @param buf [IN] message buffer * @param extMsgLen [IN] Extended message length * @param msg [OUT] Structure of the parsed extended message * * @retval HITLS_SUCCESS parsed successfully. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_PARSE_DUPLICATE_EXTENSIVE_MSG Extended message * @retval HITLS_PARSE_UNSUPPORTED_EXTENSION: unsupported extended field */ static int32_t ParseServerExBody(TLS_Ctx *ctx, uint16_t extMsgType, const uint8_t *buf, uint32_t extMsgLen, ServerHelloMsg *msg) { uint32_t bufOffset = 0u; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = extMsgLen, .bufOffset = &bufOffset}; switch (extMsgType) { case HS_EX_TYPE_POINT_FORMATS: return ParseServerPointFormats(&pkt, msg); #ifdef HITLS_TLS_FEATURE_SNI case HS_EX_TYPE_SERVER_NAME: return ParseServerServerName(&pkt, msg); #endif /* HITLS_TLS_FEATURE_SNI */ case HS_EX_TYPE_EXTENDED_MASTER_SECRET: return ParseServerExtMasterSecret(&pkt, msg); #ifdef HITLS_TLS_FEATURE_ALPN case HS_EX_TYPE_APP_LAYER_PROTOCOLS: return ParseServerSelectedAlpnProtocol( &pkt, &msg->haveSelectedAlpn, &msg->alpnSelected, &msg->alpnSelectedSize); #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_PROTO_TLS13 case HS_EX_TYPE_KEY_SHARE: return ParseServerKeyShare(&pkt, msg); case HS_EX_TYPE_PRE_SHARED_KEY: return ParseServerPreShareKey(&pkt, msg); case HS_EX_TYPE_COOKIE: return ParseServerCookie(&pkt, msg); case HS_EX_TYPE_SUPPORTED_VERSIONS: return ParseServerSupportedVersions(&pkt, msg); #endif /* HITLS_TLS_PROTO_TLS13 */ case HS_EX_TYPE_RENEGOTIATION_INFO: #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) return ParseServerSecRenegoInfo(&pkt, msg); #else return HITLS_SUCCESS; #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET case HS_EX_TYPE_SESSION_TICKET: return ParseServerTicket(&pkt, msg); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_ETM case HS_EX_TYPE_ENCRYPT_THEN_MAC: return ParseServerEncryptThenMac(&pkt, msg); #endif /* HITLS_TLS_FEATURE_ETM */ #ifdef HITLS_TLS_PROTO_TLS13 case HS_EX_TYPE_SUPPORTED_GROUPS: return HITLS_SUCCESS; #endif /* HITLS_TLS_PROTO_TLS13 */ default: break; } #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_TLS1_2_SERVER_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO | HITLS_EX_TYPE_HELLO_RETRY_REQUEST)) { return ParseCustomExtensions(pkt.ctx, pkt.buf + *pkt.bufOffset, extMsgType, extMsgLen, HITLS_EX_TYPE_TLS1_2_SERVER_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO | HITLS_EX_TYPE_HELLO_RETRY_REQUEST, NULL, 0); } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ // You need to send an alert when an unknown extended field is encountered BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15205, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unknown extension message type:%d len:%lu in server hello message.", extMsgType, extMsgLen, 0, 0); return ParseErrorProcess(pkt.ctx, HITLS_PARSE_UNSUPPORTED_EXTENSION, 0, NULL, ALERT_UNSUPPORTED_EXTENSION); } int32_t ParseServerExtension(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, ServerHelloMsg *msg) { /* Initialize the message parsing length */ uint32_t bufOffset = 0u; int32_t ret = HITLS_SUCCESS; /* Parse the extended message from server */ while (bufOffset < bufLen) { uint32_t extMsgLen = 0u; uint16_t extMsgType = HS_EX_TYPE_END; ret = ParseExHeader(ctx, &buf[bufOffset], bufLen - bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += HS_EX_HEADER_LEN; uint32_t extensionId = HS_GetExtensionTypeId(extMsgType); ret = CheckForDuplicateExtension(msg->extensionTypeMask, extensionId, ctx); if (ret != HITLS_SUCCESS) { return ret; } if (extensionId != HS_EX_TYPE_ID_UNRECOGNIZED #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION || !IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_TLS1_2_SERVER_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO | HITLS_EX_TYPE_HELLO_RETRY_REQUEST) #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ ) { if (!GetExtensionFlagValue(ctx, extensionId)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17330, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get extension type %u.", extensionId, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } msg->extensionTypeMask |= 1ULL << extensionId; } ret = ParseServerExBody(ctx, extMsgType, &buf[bufOffset], extMsgLen, msg); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += extMsgLen; } // The extended content is the last field of the serverHello message. No other data should follow. if (bufOffset != bufLen) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15206, BINGLOG_STR("parse extension failed."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } void CleanServerHelloExtension(ServerHelloMsg *msg) { if (msg == NULL) { return; } BSL_SAL_FREE(msg->pointFormats); #ifdef HITLS_TLS_FEATURE_ALPN BSL_SAL_FREE(msg->alpnSelected); #endif /* HITLS_TLS_FEATURE_ALPN */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) BSL_SAL_FREE(msg->secRenegoInfo); #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_PROTO_TLS13 BSL_SAL_FREE(msg->cookie); BSL_SAL_FREE(msg->keyShare.keyExchange); #endif /* HITLS_TLS_PROTO_TLS13 */ return; } #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/parse/src/parse_extensions_client.c
C
unknown
17,363
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "bsl_list.h" #include "hitls_error.h" #include "hitls_cert_type.h" #include "tls.h" #include "hs_extensions.h" #include "hs_common.h" #include "parse_common.h" #include "hs_ctx.h" #include "alert.h" #include "parse_extensions.h" #include "custom_extensions.h" static int32_t StorePeerSupportGroup(TLS_Ctx *ctx, ClientHelloMsg *msg) { (void)ctx; (void)msg; #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION BSL_SAL_FREE(ctx->peerInfo.groups); ctx->peerInfo.groups = (uint16_t *)BSL_SAL_Dump( msg->extension.content.supportedGroups, msg->extension.content.supportedGroupsSize * sizeof(uint16_t)); if (ctx->peerInfo.groups == NULL) { BSL_SAL_FREE(msg->extension.content.supportedGroups); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15136, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "supportedGroups dump fail when parse extensions msg.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } ctx->peerInfo.groupsSize = msg->extension.content.supportedGroupsSize; #endif return HITLS_SUCCESS; } // Parse the supported group messages. static int32_t ParseClientSupportGroups(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.haveSupportedGroups == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15132, BINGLOG_STR("ClientSupportGroups")); } uint16_t groupBufLen = 0; int32_t ret = ParseBytesToUint16(pkt, &groupBufLen); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15133, BINGLOG_STR("supported groups")); } uint16_t groupLen = groupBufLen / sizeof(uint16_t); /* If the length of the packet does not match the extended length, or the length is 0, the handshake message error * is returned */ if (((groupBufLen & 1) != 0) || ((groupLen * sizeof(uint16_t)) != (pkt->bufLen - sizeof(uint16_t))) || (groupLen == 0)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15134, BINGLOG_STR("supported groups")); } msg->extension.content.supportedGroups = (uint16_t *)BSL_SAL_Calloc(groupLen, sizeof(uint16_t)); if (msg->extension.content.supportedGroups == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15135, BINGLOG_STR("supportedGroups malloc fail."), ALERT_UNKNOWN); } for (uint32_t i = 0; i < groupLen; i++) { msg->extension.content.supportedGroups[i] = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); } msg->extension.content.supportedGroupsSize = groupLen; msg->extension.flag.haveSupportedGroups = true; return StorePeerSupportGroup(pkt->ctx, msg); } // Parse the extension item of the client hello signature algorithm. static int32_t ParseClientSignatureAlgorithms(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.haveSignatureAlgorithms == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15128, BINGLOG_STR("ClientSignatureAlgorithms")); } uint16_t signAlgBufLen = 0; int32_t ret = ParseBytesToUint16(pkt, &signAlgBufLen); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15129, BINGLOG_STR("signatureAlgorithms")); } uint16_t signatureAlgorithmsSize = signAlgBufLen / sizeof(uint16_t); // Add exception handling. The value of signAlgBufLen cannot be an odd number. Each algorithm occupies two bytes. /* If the packet length does not match the extended length or the length is 0, a handshake message error is * returned. */ if (((signAlgBufLen & 1) != 0) || (signAlgBufLen != (pkt->bufLen - *pkt->bufOffset)) || (signatureAlgorithmsSize == 0)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15130, BINGLOG_STR("signatureAlgorithms")); } /* Parse signatureAlgorithms */ uint16_t *signatureAlgorithms = (uint16_t *)BSL_SAL_Calloc(signatureAlgorithmsSize, sizeof(uint16_t)); if (signatureAlgorithms == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15131, BINGLOG_STR("signatureAlgorithms malloc fail."), ALERT_UNKNOWN); } for (uint32_t i = 0; i < signatureAlgorithmsSize; i++) { signatureAlgorithms[i] = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); } msg->extension.content.signatureAlgorithmsSize = signatureAlgorithmsSize; msg->extension.content.signatureAlgorithms = signatureAlgorithms; msg->extension.flag.haveSignatureAlgorithms = true; return HITLS_SUCCESS; } // Parse the client message in point format. static int32_t ParseClientPointFormats(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.havePointFormats == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15137, BINGLOG_STR("ClientPointFormats")); } uint8_t pointFormatsSize = 0; int32_t ret = ParseOneByteLengthField(pkt, &pointFormatsSize, &msg->extension.content.pointFormats); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15138, BINGLOG_STR("point formats")); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15140, BINGLOG_STR("pointFormats malloc fail."), ALERT_UNKNOWN); } if ((pkt->bufLen != *pkt->bufOffset) || (pointFormatsSize == 0u)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15139, BINGLOG_STR("point formats")); } msg->extension.flag.havePointFormats = true; msg->extension.content.pointFormatsSize = pointFormatsSize; pkt->ctx->haveClientPointFormats = true; return HITLS_SUCCESS; } static int32_t ParseClientExtMasterSecret(ParsePacket *pkt, ClientHelloMsg *msg) { return ParseEmptyExtension(pkt->ctx, HS_EX_TYPE_EXTENDED_MASTER_SECRET, pkt->bufLen, &msg->extension.flag.haveExtendedMasterSecret); } #ifdef HITLS_TLS_FEATURE_SNI static void SetRevMsgExtServernameInfo(ClientHelloMsg *msg, uint8_t serverNameType, uint8_t *serverName, uint16_t serverNameLen) { serverName[serverNameLen - 1] = '\0'; msg->extension.content.serverName = serverName; msg->extension.content.serverNameSize = serverNameLen; msg->extension.content.serverNameType = serverNameType; msg->extension.flag.haveServerName = true; } static int32_t ParseClientServerNameIndication(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, ClientHelloMsg *msg) { const uint32_t baseSize = sizeof(uint8_t) + sizeof(uint16_t); // serverNameType and serverName Length uint32_t bufOffset = 0; bool haveParseHostName = false; while (bufOffset + baseSize < bufLen) { /* Parse serverNameType */ uint8_t serverNameType = buf[bufOffset]; bufOffset += sizeof(uint8_t); /* Parse serverName Length */ uint16_t serverNameLen = BSL_ByteToUint16(&buf[bufOffset]); bufOffset += sizeof(uint16_t); if (bufLen < bufOffset + serverNameLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16986, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_SERVER_NAME_ERR; } if (serverNameType != 0) { bufOffset += serverNameLen; continue; } if (haveParseHostName || serverNameLen == 0 || serverNameLen > 0xff || strnlen((const char *)&buf[bufOffset], serverNameLen) != serverNameLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16987, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "serverNameLen err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_PARSE_SERVER_NAME_ERR; } haveParseHostName = true; uint8_t *serverName = (uint8_t *)BSL_SAL_Calloc((serverNameLen + 1), sizeof(uint8_t)); if (serverName == NULL) { return ParseErrorProcess(ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15127, BINGLOG_STR("server_name malloc fail."), ALERT_INTERNAL_ERROR); } (void)memcpy_s(serverName, serverNameLen + 1, &buf[bufOffset], serverNameLen); SetRevMsgExtServernameInfo(msg, serverNameType, serverName, serverNameLen + 1); bufOffset += serverNameLen; } if (bufOffset != bufLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16988, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufOffset err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_SERVER_NAME_ERR; } if (!msg->extension.flag.haveServerName) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16989, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "it is not have server name", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_PARSE_SERVER_NAME_ERR; } return HITLS_SUCCESS; } // Parse the ServerName extension item of client hello. static int32_t ParseClientServerName(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.haveServerName == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15122, BINGLOG_STR("Client ServerName")); } uint16_t serverNameListSize = 0; int32_t ret = ParseBytesToUint16(pkt, &serverNameListSize); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15123, BINGLOG_STR("ServerName")); } if ((serverNameListSize != pkt->bufLen - *pkt->bufOffset) || (serverNameListSize < sizeof(uint8_t) + sizeof(uint16_t))) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15124, BINGLOG_STR("ServerName")); } return ParseClientServerNameIndication(pkt->ctx, &pkt->buf[*pkt->bufOffset], (uint32_t)serverNameListSize, msg); } #endif /* HITLS_TLS_FEATURE_SNI */ #ifdef HITLS_TLS_FEATURE_ALPN static int32_t ParseClientAlpnProposeList(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.haveAlpn == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15141, BINGLOG_STR("alpn list")); } uint16_t alpnLen = 0; int32_t ret = ParseBytesToUint16(pkt, &alpnLen); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15142, BINGLOG_STR("alpn")); } /* If the message length does not match the extended length, or the message length is less than 2 bytes, a handshake * message error is returned */ if (((alpnLen * sizeof(uint8_t)) != (pkt->bufLen - sizeof(uint16_t))) || (alpnLen < 2)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15143, BINGLOG_STR("alpn")); } uint32_t alpnListOffset = *pkt->bufOffset; do { uint8_t alpnStringLen = pkt->buf[alpnListOffset]; alpnListOffset += alpnStringLen + 1; if (alpnListOffset > pkt->bufLen || alpnStringLen == 0) { /* can't exceed alpn extension buffer; can't be empty */ return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15144, BINGLOG_STR("alpn")); } } while (pkt->bufLen - alpnListOffset != 0); /* remaining len of alpn extension buffer */ BSL_SAL_FREE(msg->extension.content.alpnList); msg->extension.content.alpnList = (uint8_t *)BSL_SAL_Dump(&pkt->buf[*pkt->bufOffset], alpnLen); if (msg->extension.content.alpnList == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15145, BINGLOG_STR("alpn list malloc fail."), ALERT_UNKNOWN); } msg->extension.content.alpnListSize = alpnLen; msg->extension.flag.haveAlpn = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t ParseIdentities(TLS_Ctx *ctx, PreSharedKey *preSharedKey, const uint8_t *buf, uint32_t bufLen) { uint32_t bufOffset = 0u; PreSharedKey *tmp = preSharedKey; while (bufOffset + sizeof(uint16_t) < bufLen) { /* Create a linked list node */ PreSharedKey *node = (PreSharedKey *)BSL_SAL_Calloc(1, sizeof(PreSharedKey)); if (node == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16990, 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; } LIST_ADD_AFTER(&tmp->pskNode, &node->pskNode); tmp = node; /* Parse the identityLen length */ uint16_t identitySize = BSL_ByteToUint16(&buf[bufOffset]); node->identitySize = identitySize; bufOffset += sizeof(uint16_t); if ((bufOffset + identitySize + sizeof(uint32_t)) > bufLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15146, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ParseIdentities error. bufLen = %d, identitySize = %d.", bufLen, identitySize, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); return HITLS_PARSE_INVALID_MSG_LEN; } /* Parse identity */ node->identity = (uint8_t *)BSL_SAL_Calloc(1u, (node->identitySize + 1) * sizeof(uint8_t)); if (node->identity == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16991, 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(node->identity, node->identitySize + 1, &buf[bufOffset], identitySize); bufOffset += node->identitySize; node->obfuscatedTicketAge = BSL_ByteToUint32(&buf[bufOffset]); bufOffset += sizeof(uint32_t); } if (bufOffset != bufLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15147, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "IdentityEntry error. bufLen = %d ", bufLen, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_PARSE_INVALID_MSG_LEN); return HITLS_PARSE_INVALID_MSG_LEN; } return HITLS_SUCCESS; } void CleanKeyShare(KeyShare *keyShare) { ListHead *node = NULL; ListHead *tmpNode = NULL; KeyShare *cur = NULL; KeyShare *cache = keyShare; if (cache != NULL) { LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(cache->head)) { cur = LIST_ENTRY(node, KeyShare, head); LIST_REMOVE(node); BSL_SAL_FREE(cur->keyExchange); BSL_SAL_FREE(cur); } BSL_SAL_FREE(keyShare); } } /* rfc8446 4.2.8 Clients MUST NOT offer multiple KeyShareEntry values for the same group. Clients MUST NOT offer any KeyShareEntry values for groups not listed in the client's "supported_groups" extension. Servers MAY check for violations of these rules and abort the handshake with an "illegal_parameter" alert if one is violated. */ static bool KeyShareGroupAdd(uint16_t *groupSet, uint32_t groupSetCapacity, uint32_t *groupSetSize, uint16_t group) { for (uint32_t i = 0; (i < *groupSetSize) && (i + 1 < groupSetCapacity); i++) { if (groupSet[i] == group) { return false; } } groupSet[*groupSetSize] = group; *groupSetSize = *groupSetSize + 1; return true; } /** * @brief Parse KeyShareEntry and create a linked list node, * @attention The caller needs to pay attention to the function. If the function fails to be returned, the caller * releases the call. * * @param keyShare [OUT] Linked list header * @param buf [IN] message buffer * @param bufLen [IN] message length * * @return HITLS_SUCCESS parsed successfully. */ int32_t ParseKeyShare(KeyShare *keyshare, const uint8_t *buf, uint32_t bufLen, ALERT_Description *alert) { uint32_t bufOffset = 0u; KeyShare *node = keyshare; uint16_t *groupSet = (uint16_t *)BSL_SAL_Calloc(bufLen, sizeof(uint8_t)); if (groupSet == NULL) { *alert = ALERT_INTERNAL_ERROR; return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16992, "Calloc fail"); } uint32_t groupSetSize = 0; int32_t ret = HITLS_SUCCESS; while (bufOffset + sizeof(uint16_t) + sizeof(uint16_t) < bufLen) { KeyShare *tmpNode = (KeyShare *)BSL_SAL_Calloc(1u, sizeof(KeyShare)); if (tmpNode == NULL) { *alert = ALERT_INTERNAL_ERROR; BSL_SAL_FREE(groupSet); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16993, "Calloc fail"); } LIST_INIT(&tmpNode->head); LIST_ADD_AFTER(&node->head, &tmpNode->head); node = tmpNode; node->group = BSL_ByteToUint16(&buf[bufOffset]); bufOffset += sizeof(uint16_t); if (!KeyShareGroupAdd(groupSet, bufLen / sizeof(uint16_t), &groupSetSize, node->group)) { *alert = ALERT_ILLEGAL_PARAMETER; BSL_SAL_FREE(groupSet); return RETURN_ERROR_NUMBER_PROCESS(HITLS_PARSE_DUPLICATED_KEY_SHARE, BINLOG_ID16994, "key share repeated"); } node->keyExchangeSize = BSL_ByteToUint16(&buf[bufOffset]); bufOffset += sizeof(uint16_t); /* parse keyExchange */ if (node->keyExchangeSize == 0 || bufOffset + node->keyExchangeSize > bufLen) { *alert = ALERT_DECODE_ERROR; BSL_SAL_FREE(groupSet); return RETURN_ERROR_NUMBER_PROCESS(HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16995, "keyExchangeSize error"); } BSL_SAL_FREE(node->keyExchange); node->keyExchange = (uint8_t *)BSL_SAL_Dump(&buf[bufOffset], node->keyExchangeSize); if (node->keyExchange == NULL) { *alert = ALERT_INTERNAL_ERROR; BSL_SAL_FREE(groupSet); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16996, "Dump fail"); } bufOffset += node->keyExchangeSize; } BSL_SAL_FREE(groupSet); if (ret == HITLS_SUCCESS && bufOffset != bufLen) { *alert = ALERT_DECODE_ERROR; return RETURN_ERROR_NUMBER_PROCESS(HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16997, "bufLen error"); } return ret; } // Parse the KeyShare message. int32_t ParseClientKeyShare(ParsePacket *pkt, ClientHelloMsg *msg) { uint32_t bufOffset = 0u; int32_t ret = HITLS_SUCCESS; ALERT_Description alert = ALERT_UNKNOWN; do { /* Parsed extensions of the same type */ if (msg->extension.flag.haveKeyShare == true) { return RETURN_ALERT_PROCESS(pkt->ctx, HITLS_PARSE_DUPLICATE_EXTENDED_MSG, BINLOG_ID16998, "KeyShare repeated", ALERT_ILLEGAL_PARAMETER); } if (pkt->bufLen < sizeof(uint16_t)) { return RETURN_ALERT_PROCESS(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16999, "bufLen error", ALERT_DECODE_ERROR); } uint16_t keyShareLen = BSL_ByteToUint16(&pkt->buf[bufOffset]); bufOffset += sizeof(uint16_t); if (keyShareLen + bufOffset != pkt->bufLen) { return RETURN_ALERT_PROCESS(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID17000, "bufLen error", ALERT_DECODE_ERROR); } /* If the client requests hrr, keyshare can be empty */ if (keyShareLen == 0) { break; } /** Create the header of the linked list of keyShareEntry */ msg->extension.content.keyShare = (KeyShare *)BSL_SAL_Calloc(1u, sizeof(KeyShare)); if (msg->extension.content.keyShare == NULL) { return RETURN_ALERT_PROCESS(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15150, "calloc fail", ALERT_INTERNAL_ERROR); } LIST_INIT(&msg->extension.content.keyShare->head); ret = ParseKeyShare(msg->extension.content.keyShare, &pkt->buf[bufOffset], keyShareLen, &alert); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15151, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse client key share fail.", 0, 0, 0, 0); break; } } while (false); msg->extension.flag.haveKeyShare = true; if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); pkt->ctx->method.sendAlert(pkt->ctx, ALERT_LEVEL_FATAL, alert); } return ret; } // Parse the SupportedVersions message. int32_t ParseClientSupportedVersions(ParsePacket *pkt, ClientHelloMsg *msg) { /* parsed extensions of the same type */ if (msg->extension.flag.haveSupportedVers == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15152, BINGLOG_STR("ClientSupportedVersions")); } uint8_t len = 0; int32_t ret = ParseBytesToUint8(pkt, &len); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15153, BINGLOG_STR("SupportVersion")); } if ((len == 0) || ((len % sizeof(uint16_t)) != 0) || (len + *pkt->bufOffset != pkt->bufLen)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15154, BINGLOG_STR("SupportVersion")); } msg->extension.content.supportedVersions = (uint16_t *)BSL_SAL_Calloc(1u, len); if (msg->extension.content.supportedVersions == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15155, BINGLOG_STR("SupportVersion malloc fail."), ALERT_INTERNAL_ERROR); } for (uint32_t i = 0; i < len / sizeof(uint16_t); i++) { msg->extension.content.supportedVersions[i] = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); } msg->extension.content.supportedVersionsCount = len / sizeof(uint16_t); msg->extension.flag.haveSupportedVers = true; return HITLS_SUCCESS; } static int32_t ParseBinders(TLS_Ctx *ctx, PreSharedKey *preSharedKey, const uint8_t *buf, uint32_t bufLen) { uint32_t bufOffset = 0u; ListHead *node = NULL; ListHead *tmpNode = NULL; PreSharedKey *cur = NULL; PreSharedKey *cache = preSharedKey; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(cache->pskNode)) { cur = LIST_ENTRY(node, PreSharedKey, pskNode); if (bufLen < bufOffset + sizeof(uint8_t)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17001, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen error", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } uint8_t binderLen = buf[bufOffset]; bufOffset += sizeof(uint8_t); if (binderLen > (bufLen - bufOffset)) { return ParseErrorExtLengthProcess(ctx, BINLOG_ID15165, BINGLOG_STR("binder in pre share key")); } cur->binderSize = binderLen; cur->binder = (uint8_t *)BSL_SAL_Calloc(cur->binderSize, sizeof(uint8_t)); if (cur->binder == NULL) { return ParseErrorProcess(ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15166, BINGLOG_STR("pre_share_key malloc fail."), ALERT_UNKNOWN); } (void)memcpy_s(cur->binder, cur->binderSize, &buf[bufOffset], binderLen); bufOffset += binderLen; } if (bufLen != bufOffset) { return ParseErrorExtLengthProcess(ctx, BINLOG_ID15167, BINGLOG_STR("binder in pre share key")); } return HITLS_SUCCESS; } static int32_t ParseClientPreSharedKey(ParsePacket *pkt, ClientHelloMsg *msg) { if (msg->extension.flag.havePreShareKey == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15168, BINGLOG_STR("pre share key")); } uint16_t identitiesLen = 0; int32_t ret = ParseBytesToUint16(pkt, &identitiesLen); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15169, BINGLOG_STR("pre share key")); } if (pkt->bufLen <= identitiesLen + *pkt->bufOffset || identitiesLen == 0) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15170, BINGLOG_STR("pre share key")); } /* Create the header of the PskIdentity linked list */ PreSharedKey *offeredPsks = (PreSharedKey *)BSL_SAL_Calloc(1, sizeof(PreSharedKey)); if (offeredPsks == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17002, 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; } msg->extension.content.preSharedKey = offeredPsks; LIST_INIT(&offeredPsks->pskNode); ret = ParseIdentities(pkt->ctx, offeredPsks, &pkt->buf[*pkt->bufOffset], identitiesLen); if (ret != HITLS_SUCCESS) { return ret; } *pkt->bufOffset += identitiesLen; msg->truncateHelloLen = &pkt->buf[*pkt->bufOffset] - pkt->ctx->hsCtx->msgBuf; if (pkt->bufLen < sizeof(uint16_t) + *pkt->bufOffset) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17003, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen error", 0, 0, 0, 0); pkt->ctx->method.sendAlert(pkt->ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } /* Obtain the length of the binder list len */ uint16_t bindersLen = BSL_ByteToUint16(&pkt->buf[*pkt->bufOffset]); *pkt->bufOffset += sizeof(uint16_t); if (pkt->bufLen != *pkt->bufOffset + bindersLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17004, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen error", 0, 0, 0, 0); pkt->ctx->method.sendAlert(pkt->ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } ret = ParseBinders(pkt->ctx, offeredPsks, &pkt->buf[*pkt->bufOffset], bindersLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15171, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse binders extensions msg.", 0, 0, 0, 0); return ret; } msg->extension.flag.havePreShareKey = true; return HITLS_SUCCESS; } static int32_t ParseClientTrustedCaList(ParsePacket *pkt, ClientHelloMsg *msg) { /* Refer to the CAList parsing method of the CertificateRequest Msg. */ /* Parsed extensions of the same type */ if (msg->extension.flag.haveCA == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15172, BINGLOG_STR("certificate_authorities")); } uint16_t distinguishedNamesLen = 0; int32_t ret = ParseBytesToUint16(pkt, &distinguishedNamesLen); if (ret != HITLS_SUCCESS) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15173, BINGLOG_STR("CaList")); } /* https://www.rfc-editor.org/rfc/rfc8446#section-4.2.4 opaque DistinguishedName<1..2^16-1> struct { DistinguishedName authorities<3..2^16-1> } CertificateAuthoritiesExtension */ if (distinguishedNamesLen != (pkt->bufLen - *pkt->bufOffset) || (distinguishedNamesLen < 3)) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15174, BINGLOG_STR("CaList")); } FreeDNList(msg->extension.content.caList); msg->extension.content.caList = ParseDNList(&pkt->buf[*pkt->bufOffset], distinguishedNamesLen); if (msg->extension.content.caList == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17005, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ParseDNList fail", 0, 0, 0, 0); pkt->ctx->method.sendAlert(pkt->ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); BSL_ERR_PUSH_ERROR(HITLS_PARSE_CA_LIST_ERR); return HITLS_PARSE_CA_LIST_ERR; } HITLS_TrustedCAList *tmp = pkt->ctx->peerInfo.caList; pkt->ctx->peerInfo.caList = msg->extension.content.caList; msg->extension.content.caList = tmp; msg->extension.flag.haveCA = true; return HITLS_SUCCESS; } static int32_t ParseClientPskKeyExModes(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.havePskExMode == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15175, BINGLOG_STR("pskKeyExchangeMode")); } uint8_t len = 0; int32_t ret = ParseOneByteLengthField(pkt, &len, &msg->extension.content.keModes); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15176, BINGLOG_STR("pskKeyExchangeMode")); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15177, BINGLOG_STR("pskKeyExchangeMode malloc fail."), ALERT_UNKNOWN); } if ((pkt->bufLen != *pkt->bufOffset) || (len == 0u)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17006, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bufLen error", 0, 0, 0, 0); pkt->ctx->method.sendAlert(pkt->ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } msg->extension.content.keModesSize = len; msg->extension.flag.havePskExMode = true; return HITLS_SUCCESS; } static int32_t ParseClientCookie(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.haveCookie == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15178, BINGLOG_STR("cookie")); } int32_t ret = ParseExCookie(pkt->buf, pkt->bufLen, &msg->extension.content.cookie, &msg->extension.content.cookieLen); if (ret != HITLS_SUCCESS) { return ret; } msg->extension.flag.haveCookie = true; return HITLS_SUCCESS; } static int32_t ParseClientPostHsAuth(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.havePostHsAuth == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15182, BINGLOG_STR("post_handshake_auth")); } /* The length of the extended data field of the rfc 8446 "post_handshake_auth" extension is 0. */ if (pkt->bufLen != 0) { return ParseErrorExtLengthProcess(pkt->ctx, BINLOG_ID15183, BINGLOG_STR("post_handshake_auth")); } msg->extension.flag.havePostHsAuth = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t ParseClientSecRenegoInfo(ParsePacket *pkt, ClientHelloMsg *msg) { /* Parsed extensions of the same type */ if (msg->extension.flag.haveSecRenego == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15187, BINGLOG_STR("renegotiation info")); } uint8_t secRenegoInfoSize = 0; uint8_t *secRenegoInfo = NULL; int32_t ret = ParseSecRenegoInfo(pkt->ctx, pkt->buf, pkt->bufLen, &secRenegoInfo, &secRenegoInfoSize); if (ret != HITLS_SUCCESS) { return ret; } msg->extension.content.secRenegoInfo = secRenegoInfo; msg->extension.content.secRenegoInfoSize = secRenegoInfoSize; msg->extension.flag.haveSecRenego = true; return HITLS_SUCCESS; } #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_ETM static int32_t ParseClientEncryptThenMac(ParsePacket *pkt, ClientHelloMsg *msg) { return ParseEmptyExtension(pkt->ctx, HS_EX_TYPE_ENCRYPT_THEN_MAC, pkt->bufLen, &msg->extension.flag.haveEncryptThenMac); } #endif /* HITLS_TLS_FEATURE_ETM */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET static int32_t ParseClientTicket(ParsePacket *pkt, ClientHelloMsg *msg) { uint8_t *ticket = NULL; /* ticket */ /* Parsed extensions of the same type */ if (msg->extension.flag.haveTicket == true) { return ParseDupExtProcess(pkt->ctx, BINLOG_ID15975, BINGLOG_STR("tiket")); } if (pkt->bufLen != 0) { ticket = (uint8_t *)BSL_SAL_Dump(&pkt->buf[0], pkt->bufLen); if (ticket == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15976, BINGLOG_STR("ticket malloc fail."), ALERT_INTERNAL_ERROR); } } msg->extension.content.ticket = ticket; msg->extension.content.ticketSize = pkt->bufLen; msg->extension.flag.haveTicket = true; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ // parses the extension message from client static int32_t ParseClientExBody(TLS_Ctx *ctx, uint16_t extMsgType, const uint8_t *buf, uint32_t extMsgLen, ClientHelloMsg *msg) { uint32_t bufOffset = 0u; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = extMsgLen, .bufOffset = &bufOffset}; static struct { uint16_t exMsgType; /**< Extension type of message*/ int32_t (*parseFunc)(ParsePacket *, ClientHelloMsg *); /**< Hook for packing extensions*/ } extMsgList [] = { { .exMsgType = HS_EX_TYPE_POINT_FORMATS, .parseFunc = ParseClientPointFormats }, { .exMsgType = HS_EX_TYPE_SUPPORTED_GROUPS, .parseFunc = ParseClientSupportGroups }, { .exMsgType = HS_EX_TYPE_SIGNATURE_ALGORITHMS, .parseFunc = ParseClientSignatureAlgorithms}, #ifdef HITLS_TLS_FEATURE_SNI { .exMsgType = HS_EX_TYPE_SERVER_NAME, .parseFunc = ParseClientServerName}, #endif /* HITLS_TLS_FEATURE_SNI */ { .exMsgType = HS_EX_TYPE_EXTENDED_MASTER_SECRET, .parseFunc = ParseClientExtMasterSecret}, #ifdef HITLS_TLS_FEATURE_ALPN { .exMsgType = HS_EX_TYPE_APP_LAYER_PROTOCOLS, .parseFunc = ParseClientAlpnProposeList}, #endif #ifdef HITLS_TLS_PROTO_TLS13 { .exMsgType = HS_EX_TYPE_SUPPORTED_VERSIONS, .parseFunc = ParseClientSupportedVersions}, { .exMsgType = HS_EX_TYPE_PRE_SHARED_KEY, .parseFunc = ParseClientPreSharedKey}, { .exMsgType = HS_EX_TYPE_PSK_KEY_EXCHANGE_MODES, .parseFunc = ParseClientPskKeyExModes}, { .exMsgType = HS_EX_TYPE_COOKIE, .parseFunc = ParseClientCookie}, { .exMsgType = HS_EX_TYPE_CERTIFICATE_AUTHORITIES, .parseFunc = ParseClientTrustedCaList}, { .exMsgType = HS_EX_TYPE_POST_HS_AUTH, .parseFunc = ParseClientPostHsAuth}, { .exMsgType = HS_EX_TYPE_KEY_SHARE, .parseFunc = ParseClientKeyShare}, #endif /* HITLS_TLS_PROTO_TLS13 */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) { .exMsgType = HS_EX_TYPE_RENEGOTIATION_INFO, .parseFunc = ParseClientSecRenegoInfo}, #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET { .exMsgType = HS_EX_TYPE_SESSION_TICKET, .parseFunc = ParseClientTicket}, #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_ETM { .exMsgType = HS_EX_TYPE_ENCRYPT_THEN_MAC, .parseFunc = ParseClientEncryptThenMac}, #endif /* HITLS_TLS_FEATURE_ETM */ }; for (uint32_t index = 0; index < sizeof(extMsgList) / sizeof(extMsgList[0]); index++) { if (extMsgList[index].exMsgType == extMsgType) { return extMsgList[index].parseFunc(&pkt, msg); } } #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_CLIENT_HELLO)) { return ParseCustomExtensions(pkt.ctx, pkt.buf + *pkt.bufOffset, extMsgType, extMsgLen, HITLS_EX_TYPE_CLIENT_HELLO, NULL, 0); } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ // Ignore unknown extensions BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15188, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "unknown extension message type:%d len:%lu in client hello message.", extMsgType, extMsgLen, 0, 0); return HITLS_SUCCESS; } int32_t ParseClientExtension(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, ClientHelloMsg *msg) { uint32_t bufOffset = 0u; int32_t ret = HITLS_SUCCESS; uint8_t extensionCount = 0; /* Parse the extended message from client */ while (bufOffset < bufLen) { uint16_t extMsgType = HS_EX_TYPE_END; uint32_t extMsgLen = 0u; ret = ParseExHeader(ctx, &buf[bufOffset], bufLen - bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += HS_EX_HEADER_LEN; uint32_t extensionId = HS_GetExtensionTypeId(extMsgType); ret = CheckForDuplicateExtension(msg->extensionTypeMask, extensionId, ctx); if (ret != HITLS_SUCCESS) { return ret; } if (extensionId != HS_EX_TYPE_ID_UNRECOGNIZED #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION || !IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_CLIENT_HELLO) #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ ) { msg->extensionTypeMask |= 1ULL << extensionId; } ret = ParseClientExBody(ctx, extMsgType, &buf[bufOffset], extMsgLen, msg); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += extMsgLen; /* rfc8446 4.2.11. The "pre_shared_key" extension MUST be the last extension in the ClientHello (this facilitates implementation as described below). Servers MUST check that it is the last extension and otherwise fail the handshake with an "illegal_parameter" alert. */ if (extMsgType == HS_EX_TYPE_PRE_SHARED_KEY && bufOffset != bufLen) { return ParseErrorProcess(ctx, HITLS_PARSE_PRE_SHARED_KEY_FAILED, BINLOG_ID16136, BINGLOG_STR("psk is not the last extension."), ALERT_ILLEGAL_PARAMETER); } extensionCount++; } /* The extended content is the last field of the clientHello packet and no other data is allowed. If the parsed * length is inconsistent with the buffer length, an error code is returned */ if (bufOffset != bufLen) { return ParseErrorExtLengthProcess(ctx, BINLOG_ID15192, BINGLOG_STR("client hello")); } #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB if (ctx->globalConfig != NULL && ctx->globalConfig->clientHelloCb != NULL) { msg->extensionBuff = BSL_SAL_Dump(buf, bufLen); if (msg->extensionBuff == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return ParseErrorProcess(ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID17356, BINGLOG_STR("extensionBuff dump fail."), ALERT_INTERNAL_ERROR); } msg->extensionBuffLen = bufLen; msg->extensionCount = extensionCount; } #else (void)extensionCount; #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 void CleanPreShareKey(PreSharedKey *preSharedKey) { ListHead *node = NULL; ListHead *tmpNode = NULL; PreSharedKey *cur = NULL; PreSharedKey *cache = preSharedKey; if (cache != NULL) { LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(cache->pskNode)) { cur = LIST_ENTRY(node, PreSharedKey, pskNode); LIST_REMOVE(node); BSL_SAL_FREE(cur->identity); BSL_SAL_FREE(cur->binder); BSL_SAL_FREE(cur); } BSL_SAL_FREE(preSharedKey); } } #endif /* HITLS_TLS_PROTO_TLS13 */ void CleanClientHelloExtension(ClientHelloMsg *msg) { if (msg == NULL) { return; } /* Release the Client Hello extension message structure */ BSL_SAL_FREE(msg->extension.content.supportedGroups); BSL_SAL_FREE(msg->extension.content.pointFormats); BSL_SAL_FREE(msg->extension.content.signatureAlgorithms); #ifdef HITLS_TLS_FEATURE_ALPN BSL_SAL_FREE(msg->extension.content.alpnList); #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_FEATURE_SNI BSL_SAL_FREE(msg->extension.content.serverName); #endif /* HITLS_TLS_FEATURE_SNI */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) BSL_SAL_FREE(msg->extension.content.secRenegoInfo); #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET BSL_SAL_FREE(msg->extension.content.ticket); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_PROTO_TLS13 BSL_SAL_FREE(msg->extension.content.signatureAlgorithmsCert); BSL_SAL_FREE(msg->extension.content.supportedVersions); BSL_SAL_FREE(msg->extension.content.keModes); BSL_SAL_FREE(msg->extension.content.cookie); CleanKeyShare(msg->extension.content.keyShare); msg->extension.content.keyShare = NULL; CleanPreShareKey(msg->extension.content.preSharedKey); msg->extension.content.preSharedKey = NULL; FreeDNList(msg->extension.content.caList); msg->extension.content.caList = NULL; #endif /* HITLS_TLS_PROTO_TLS13 */ return; } #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/parse/src/parse_extensions_server.c
C
unknown
41,347
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "hs_msg.h" #include "parse_msg.h" #include "parse_common.h" int32_t ParseFinished(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { /* if the cache length is 0, return an error code */ if (bufLen == 0u) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15830, BINGLOG_STR("parse 0 length finish"), ALERT_DECODE_ERROR); } FinishedMsg *msg = &hsMsg->body.finished; /* get the data of verify */ BSL_SAL_FREE(msg->verifyData); msg->verifyData = BSL_SAL_Malloc(bufLen); if (msg->verifyData == NULL) { return ParseErrorProcess(ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15831, BINGLOG_STR("verifyData malloc fail"), ALERT_UNKNOWN); } (void)memcpy_s(msg->verifyData, bufLen, buf, bufLen); msg->verifyDataSize = bufLen; return HITLS_SUCCESS; } void CleanFinished(FinishedMsg *msg) { if (msg != NULL) { BSL_SAL_FREE(msg->verifyData); } return; }
2301_79861745/bench_create
tls/handshake/parse/src/parse_finished.c
C
unknown
1,732
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hs_msg.h" #include "parse_common.h" #include "parse_extensions.h" #include "parse_msg.h" int32_t ParseHelloVerifyRequest(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { int32_t ret = HITLS_SUCCESS; HelloVerifyRequestMsg *msg = &hsMsg->body.helloVerifyReq; uint32_t bufOffset = 0; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &bufOffset}; ret = ParseVersion(&pkt, &msg->version); if (ret != HITLS_SUCCESS) { return ret; } ret = ParseCookie(&pkt, &msg->cookieLen, &msg->cookie); if (ret != HITLS_SUCCESS) { CleanHelloVerifyRequest(msg); return ret; } // The cookie content is the last field of the helloVerifyRequest message. No other data should follow. if (bufLen != bufOffset) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID17335, BINGLOG_STR("hello verify request packet length error."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } void CleanHelloVerifyRequest(HelloVerifyRequestMsg *msg) { if (msg == NULL) { return; } BSL_SAL_FREE(msg->cookie); return; } #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/parse/src/parse_hello_verify_request.c
C
unknown
2,003
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_KEY_UPDATE #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_msg.h" #include "parse_common.h" int32_t ParseKeyUpdate(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { uint32_t bufOffset = 0u; /* if the cache length is not 1, return an error code */ if (bufLen != 1u) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15868, BINGLOG_STR("keyupdate length is not 1"), ALERT_DECODE_ERROR); } KeyUpdateMsg *msg = &hsMsg->body.keyUpdate; msg->requestUpdate = buf[bufOffset]; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_KEY_UPDATE */
2301_79861745/bench_create
tls/handshake/parse/src/parse_key_update.c
C
unknown
1,331
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 PARSE_MSG_H #define PARSE_MSG_H #include <stdint.h> #include "tls.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Parse client Hello message * * @param ctx [IN] TLS context * @param data [IN] Message buffer * @param len [IN] Message buffer length * @param hsMsg [OUT] Parsed message structure * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG Extension duplicated */ int32_t ParseClientHello(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_Msg *hsMsg); /** * @brief Parse Server Hello message * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG Extension duplicated */ int32_t ParseServerHello(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse Hello Verify Request message * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_PARSE_DUPLICATE_EXTENDED_MSG Extension duplicated */ int32_t ParseHelloVerifyRequest(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse TLS 1.3 EncryptedExtensions message * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @return HITLS_SUCCESS * HITLS_INVALID_PARAMETERS The input parameter is a null pointer * HITLS_ALERT_FATAL Message error * HITLS_MEMALLOC_FAIL Memory allocated failed */ int32_t ParseEncryptedExtensions(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse certificate message * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @retval HITLS_SUCCESS * @retval HITLSPARSE_CERT_ERR Failed to parse the certificate * @retval HITLSPARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseCertificate(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse TLS 1.3 certificate message * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @retval HITLS_SUCCESS * @retval HITLSPARSE_CERT_ERR Failed to parse the certificate * @retval HITLSPARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t Tls13ParseCertificate(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse Server Key Exchange message * * @param ctx [IN] TLS context * @param data [IN] Message buffer * @param len [IN] Message buffer length * @param hsMsg [OUT] Parsed message structure * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_PARSE_UNSUPPORT_KX_CURVE_TYPE Unsupported ECC curve type * @retval HITLS_PARSE_ECDH_PUBKEY_ERR Failed to parse the ECDH public key * @retval HITLS_PARSE_ECDH_SIGN_ERR Failed to parse the ECDH signature * @retval HITLS_PARSE_UNSUPPORT_KX_ALG Unsupported key exchange algorithm */ int32_t ParseServerKeyExchange(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_Msg *hsMsg); /** * @brief Parse certificate request message, which is applicable to TLS1.2/DTLS/TLS1.3 protocols * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_MEMALLOC_FAIL Memory allocated failed */ int32_t ParseCertificateRequest(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse TLS1.3 certificate request message * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_MEMALLOC_FAIL Memory allocated failed */ int32_t Tls13ParseCertificateRequest(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse Client Key Exchange message * * @param ctx [IN] TLS context * @param data [IN] Message buffer * @param len [IN] Message buffer length * @param hsMsg [OUT] Parsed Message structure * * @retval HITLS_SUCCESS * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseClientKeyExchange(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_Msg *hsMsg); /** * @brief Parse Certificate Verify message * * @param ctx [IN] TLS context * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * @param hsMsg [OUT] Message structure * * @retval HITLS_SUCCESS * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect * @retval HITLS_MEMALLOC_FAIL Memory allocated failed */ int32_t ParseCertificateVerify(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse Finished message * * @param ctx [IN] TLS context * @param hsMsg [OUT] Message structure * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseFinished(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse KeyUpdate message * * @param ctx [IN] TLS context * @param hsMsg [OUT] Message structure * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseKeyUpdate(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Parse new sessionticket message * * @param ctx [IN] TLS context * @param hsMsg [OUT] Message structure * @param buf [IN] Message buffer * @param bufLen [IN] Maximum message length * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect */ int32_t ParseNewSessionTicket(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg); /** * @brief Free the memory allocated in the Client Hello message structure * * @param msg [IN] Message structure */ void CleanClientHello(ClientHelloMsg *msg); /** * @brief Free the memory allocated in the Server Hello message structure * * @param msg [IN] Message structure */ void CleanServerHello(ServerHelloMsg *msg); /** * @brief Free the memory allocated in the Hello Verify Request message structure * * @param msg [IN] Message structure */ void CleanHelloVerifyRequest(HelloVerifyRequestMsg *msg); /** * @brief Free the memory allocated in the EncryptedExtensions message structure * * @param msg [IN] Message structure */ void CleanEncryptedExtensions(EncryptedExtensions *msg); /** * @brief Free the memory allocated in the certificate message structure * * @param msg [IN] Message structure */ void CleanCertificate(CertificateMsg *msg); /** * @brief Free the memory allocated in the ServerKeyExchangeMsg message structure * * @param msg [IN] Message structure */ void CleanServerKeyExchange(ServerKeyExchangeMsg *msg); /** * @brief Free the memory allocated in the Certificate Request message structure * * @param msg [IN] Message structure */ void CleanCertificateRequest(CertificateRequestMsg *msg); /** * @brief Free the memory allocated in the Client KeyExchange message structure * * @param msg [IN] Message structure */ void CleanClientKeyExchange(ClientKeyExchangeMsg *msg); /** * @brief Free the memory allocated in the Certificate Verify message structure * * @param msg [IN] Message structure */ void CleanCertificateVerify(CertificateVerifyMsg *msg); /** * @brief Free the memory allocated in the NewSessionTicket message structure * * @param msg [IN] Message structure */ void CleanNewSessionTicket(NewSessionTicketMsg *msg); /** * @brief Free the memory allocated in the Finished message structure * * @param msg [IN] Message structure */ void CleanFinished(FinishedMsg *msg); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end PARSE_MSG_H */
2301_79861745/bench_create
tls/handshake/parse/src/parse_msg.h
C
unknown
10,148
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_TLS_HOST_CLIENT) && defined(HITLS_TLS_FEATURE_SESSION_TICKET) #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "tls.h" #include "hs_msg.h" #include "hs_common.h" #include "hs_extensions.h" #include "parse_msg.h" #include "parse_common.h" #include "parse_extensions.h" #include "custom_extensions.h" #ifdef HITLS_TLS_PROTO_TLS13 static int32_t ParseTicketNonce(ParsePacket *pkt, NewSessionTicketMsg *msg) { uint8_t ticketNonceSize = 0; const char *logStr = BINGLOG_STR("ParseOneByteLengthField fail"); int32_t ret = ParseOneByteLengthField(pkt, &ticketNonceSize, &msg->ticketNonce); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID17010, logStr, ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID17011, logStr, ALERT_INTERNAL_ERROR); } if (ticketNonceSize == 0) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID17012, logStr, ALERT_DECODE_ERROR); } msg->ticketNonceSize = (uint32_t)ticketNonceSize; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ static int32_t ParseTicket(ParsePacket *pkt, NewSessionTicketMsg *msg) { bool isTls13 = (pkt->ctx->negotiatedInfo.version == HITLS_VERSION_TLS13); uint16_t ticketSize = 0; /* rfc5077 3.3 If the server does not include a ticket after including the SessionTicket extension in the ServerHello, it sends a zero-length ticket in the NewSessionTicket handshake message */ int32_t ret = ParseTwoByteLengthField(pkt, &ticketSize, &msg->ticket); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16012, BINGLOG_STR("parse ticketSize failed."), ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15968, BINGLOG_STR("malloc ticket failed."), ALERT_UNKNOWN); } /* TLS1.3 does not allow the ticket length to be 0 */ if ((isTls13 && (ticketSize == 0)) || (!isTls13 && (pkt->bufLen != *pkt->bufOffset))) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15967, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse sesionticket message failed, bufLen %u, ticket size %u.", pkt->bufLen, ticketSize, 0, 0); return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, 0, NULL, ALERT_DECODE_ERROR); } msg->ticketSize = (uint32_t)ticketSize; return HITLS_SUCCESS; } int32_t ParseNewSessionTicketExtension(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, NewSessionTicketMsg *msg) { uint32_t bufOffset = 0u; int32_t ret = HITLS_SUCCESS; while (bufOffset < bufLen) { uint32_t extMsgLen = 0u; uint16_t extMsgType = HS_EX_TYPE_END; ret = ParseExHeader(ctx, &buf[bufOffset], bufLen - bufOffset, &extMsgType, &extMsgLen); if (ret != HITLS_SUCCESS) { return ret; } bufOffset += HS_EX_HEADER_LEN; if (bufLen - bufOffset >= extMsgLen) { uint32_t hsExTypeId = HS_GetExtensionTypeId(extMsgType); if (hsExTypeId != HS_EX_TYPE_ID_UNRECOGNIZED #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION || !IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET) #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ ) { msg->extensionTypeMask |= 1ULL << hsExTypeId; } #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsParseNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), extMsgType, HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET)) { ret = ParseCustomExtensions(ctx, buf + bufOffset, extMsgType, extMsgLen, HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET, NULL, 0); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ bufOffset += extMsgLen; } else { return HITLS_PARSE_INVALID_MSG_LEN; } } if (bufOffset != bufLen) { return ParseErrorProcess(ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15206, BINGLOG_STR("parse extension failed."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } static int32_t ParseNewSessionTicketExtensions(ParsePacket *pkt, NewSessionTicketMsg *msg) { uint16_t exMsgLen = 0; const char *logStr = BINGLOG_STR("parse extension length failed."); int32_t ret = ParseBytesToUint16(pkt, &exMsgLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15788, logStr, ALERT_DECODE_ERROR); } if (exMsgLen != (pkt->bufLen - *pkt->bufOffset)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15789, logStr, ALERT_DECODE_ERROR); } if (exMsgLen == 0u) { return HITLS_SUCCESS; } return ParseNewSessionTicketExtension(pkt->ctx, &pkt->buf[*pkt->bufOffset], exMsgLen, msg); } int32_t ParseNewSessionTicket(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { uint32_t bufOffset = 0u; NewSessionTicketMsg *msg = &hsMsg->body.newSessionTicket; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &bufOffset}; const char *logStr = BINGLOG_STR("parse sesionticket len fail."); int32_t ret = ParseBytesToUint32(&pkt, &msg->ticketLifetimeHint); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15966, logStr, ALERT_DECODE_ERROR); } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { uint32_t ticketAgeAdd = 0; ret = ParseBytesToUint32(&pkt, &ticketAgeAdd); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt.ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID16013, logStr, ALERT_DECODE_ERROR); } msg->ticketAgeAdd = ticketAgeAdd; ret = ParseTicketNonce(&pkt, msg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16014, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse ticket nonce failed.", 0, 0, 0, 0); return ret; } } #endif /* HITLS_TLS_PROTO_TLS13 */ ret = ParseTicket(&pkt, msg); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { ret = ParseNewSessionTicketExtensions(&pkt, msg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17352, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse ticket extensions failed.", 0, 0, 0, 0); return ret; } } #endif /* HITLS_TLS_PROTO_TLS13 */ return HITLS_SUCCESS; } void CleanNewSessionTicket(NewSessionTicketMsg *msg) { if (msg == NULL) { return; } BSL_SAL_FREE(msg->ticketNonce); BSL_SAL_FREE(msg->ticket); msg->ticketSize = 0; msg->ticketNonceSize = 0; return; } #endif /* HITLS_TLS_HOST_CLIENT || HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/parse/src/parse_new_sesion_ticket.c
C
unknown
8,047
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hs_msg.h" #include "parse_common.h" #include "parse_extensions.h" #include "parse_msg.h" static int32_t ParseServerHelloCipherSuite(ParsePacket *pkt, ServerHelloMsg *msg) { int32_t ret = ParseBytesToUint16(pkt, &msg->cipherSuite); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15785, BINGLOG_STR("parse cipherSuites failed."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } static int32_t ParseServerHelloCompressionMethod(ParsePacket *pkt) { uint8_t comMethod = 0; int32_t ret = ParseBytesToUint8(pkt, &comMethod); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15786, BINGLOG_STR("parse compression method failed."), ALERT_DECODE_ERROR); } if (comMethod != 0u) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_COMPRESSION_METHOD_ERR, BINLOG_ID15787, BINGLOG_STR("client does not support compression format."), ALERT_ILLEGAL_PARAMETER); } return HITLS_SUCCESS; } static int32_t ParseServerHelloExtensions(ParsePacket *pkt, ServerHelloMsg *msg) { uint16_t exMsgLen = 0; const char *logStr = BINGLOG_STR("parse extension length failed."); int32_t ret = ParseBytesToUint16(pkt, &exMsgLen); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15788, logStr, ALERT_DECODE_ERROR); } if (exMsgLen != (pkt->bufLen - *pkt->bufOffset)) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15789, logStr, ALERT_DECODE_ERROR); } if (exMsgLen == 0u) { return HITLS_SUCCESS; } return ParseServerExtension(pkt->ctx, &pkt->buf[*pkt->bufOffset], exMsgLen, msg); } int32_t ParseServerHello(TLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HS_Msg *hsMsg) { int32_t ret = HITLS_SUCCESS; ServerHelloMsg *msg = &hsMsg->body.serverHello; uint32_t bufOffset = 0; ParsePacket pkt = {.ctx = ctx, .buf = buf, .bufLen = bufLen, .bufOffset = &bufOffset}; ret = ParseVersion(&pkt, &msg->version); if (ret != HITLS_SUCCESS) { return ret; } ret = ParseRandom(&pkt, msg->randomValue, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { return ret; } ret = ParseSessionId(&pkt, &msg->sessionIdSize, &msg->sessionId); if (ret != HITLS_SUCCESS) { return ret; } ret = ParseServerHelloCipherSuite(&pkt, msg); if (ret != HITLS_SUCCESS) { return ret; } ret = ParseServerHelloCompressionMethod(&pkt); if (ret != HITLS_SUCCESS) { return ret; } /* If the buf length is equal to the offset length, return HITLS_SUCCESS. */ if (bufLen == bufOffset) { // ServerHello is optionally followed by extension data return HITLS_SUCCESS; } return ParseServerHelloExtensions(&pkt, msg); } void CleanServerHello(ServerHelloMsg *msg) { if (msg == NULL) { return; } BSL_SAL_FREE(msg->sessionId); CleanServerHelloExtension(msg); return; } #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/parse/src/parse_server_hello.c
C
unknown
3,982
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_TLS_HOST_CLIENT #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_config.h" #include "tls_config.h" #include "cert_method.h" #include "cert.h" #include "cipher_suite.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_common.h" #include "parse_msg.h" #include "parse_common.h" // Parse signature algorithm in the context message. int32_t ParseSignAlgorithm(ParsePacket *pkt, uint16_t *signAlg) { uint16_t signScheme = 0; TLS_Ctx *ctx = pkt->ctx; int32_t ret = ParseBytesToUint16(pkt, &signScheme); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15306, BINGLOG_STR("parse signAlgorithm failed in serverKeyEx."), ALERT_DECODE_ERROR); } ret = CheckPeerSignScheme(ctx, ctx->hsCtx->peerCert, signScheme); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, ret, 0, NULL, ALERT_ILLEGAL_PARAMETER); } uint32_t i = 0; /* If the client_hello message contains the signature_algorithms extension, the server_key_exchange message must use * the signature algorithm in the extension. */ for (i = 0; i < ctx->config.tlsConfig.signAlgorithmsSize; i++) { if (ctx->config.tlsConfig.signAlgorithms[i] == signScheme) { break; } } if (i == ctx->config.tlsConfig.signAlgorithmsSize) { /* Handshake failed because it is not an extended signature algorithm. */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15307, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "check serverKeyEx signature algo fail: 0x%x is not included in client hello.", signScheme, 0, 0, 0); return ParseErrorProcess(pkt->ctx, HITLS_PARSE_UNSUPPORT_SIGN_ALG, 0, NULL, ALERT_HANDSHAKE_FAILURE); } #ifdef HITLS_TLS_FEATURE_SECURITY if (SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_SIGALG_CHECK, 0, signScheme, NULL) != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17132, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "signScheme 0x%x SslCheck fail", signScheme, 0, 0, 0); return ParseErrorProcess(pkt->ctx, HITLS_PARSE_UNSUPPORT_SIGN_ALG, 0, NULL, ALERT_HANDSHAKE_FAILURE); } #endif *signAlg = signScheme; return HITLS_SUCCESS; } // Parse the signature in the ECDHE kx message. int32_t ParseSignature(ParsePacket *pkt, uint16_t *signSize, uint8_t **signData) { int32_t ret = ParseTwoByteLengthField(pkt, signSize, signData); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15308, BINGLOG_STR("parse serverkeyEx signature failed."), ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15311, BINGLOG_STR("signData malloc fail."), ALERT_UNKNOWN); } if (pkt->bufLen != *pkt->bufOffset) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15308, BINGLOG_STR("parse serverkeyEx signature failed."), ALERT_DECODE_ERROR); } if (*signSize == 0) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15310, BINGLOG_STR("length of server signSize is 0."), ALERT_ILLEGAL_PARAMETER); } return HITLS_SUCCESS; } static void GetServerKeyExSignParam(const ServerKeyExchangeMsg *msg, CERT_SignParam *signParam, HITLS_SignHashAlgo *signScheme) { if (msg->keyExType == HITLS_KEY_EXCH_ECDHE) { *signScheme = msg->keyEx.ecdh.signAlgorithm; signParam->sign = msg->keyEx.ecdh.signData; signParam->signLen = msg->keyEx.ecdh.signSize; } else if (msg->keyExType == HITLS_KEY_EXCH_DHE) { *signScheme = msg->keyEx.dh.signAlgorithm; signParam->sign = msg->keyEx.dh.signData; signParam->signLen = msg->keyEx.dh.signSize; } return; } int32_t VerifySignature(TLS_Ctx *ctx, const uint8_t *kxData, uint32_t kxDataLen, ServerKeyExchangeMsg *msg) { CERT_SignParam signParam = {0}; HITLS_SignHashAlgo signScheme = 0; GetServerKeyExSignParam(msg, &signParam, &signScheme); /* Obtain the signature algorithm and hash algorithm */ if (!CFG_GetSignParamBySchemes(ctx, signScheme, &signParam.signAlgo, &signParam.hashAlgo)) { return ParseErrorProcess(ctx, HITLS_PARSE_GET_SIGN_PARA_ERR, BINLOG_ID15312, BINGLOG_STR("get sign param fail."), ALERT_ILLEGAL_PARAMETER); } /* Obtain all signature data (random number + server kx content). */ uint8_t *data = HS_PrepareSignData(ctx, kxData, kxDataLen, &signParam.dataLen); if (data == NULL) { return ParseErrorProcess(ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15313, BINGLOG_STR("data malloc fail."), ALERT_INTERNAL_ERROR); } if (ctx->hsCtx->peerCert == NULL) { BSL_SAL_FREE(data); return ParseErrorProcess(ctx, HITLS_PARSE_VERIFY_SIGN_FAIL, BINLOG_ID17013, BINGLOG_STR("peerCert null"), ALERT_CERTIFICATE_REQUIRED); } HITLS_CERT_X509 *cert = SAL_CERT_PairGetX509(ctx->hsCtx->peerCert); HITLS_CERT_Key *pubkey = NULL; int32_t ret = SAL_CERT_X509Ctrl(&(ctx->config.tlsConfig), cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17014, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GET_PUB_KEY fail", 0, 0, 0, 0); BSL_SAL_FREE(data); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } signParam.data = data; ret = SAL_CERT_VerifySign(ctx, pubkey, &signParam); SAL_CERT_KeyFree(ctx->config.tlsConfig.certMgrCtx, pubkey); BSL_SAL_FREE(data); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(ctx, HITLS_PARSE_VERIFY_SIGN_FAIL, BINLOG_ID15314, BINGLOG_STR("verify signature fail."), ALERT_DECRYPT_ERROR); } return HITLS_SUCCESS; } #ifdef HITLS_TLS_SUITE_KX_ECDHE static int32_t ParseEcdhePublicKey(ParsePacket *pkt, ServerEcdh *ecdh) { const char *logStr = BINGLOG_STR("parse ecdhe public key fail."); uint8_t pubKeySize = 0; int32_t ret = ParseBytesToUint8(pkt, &pubKeySize); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15298, logStr, ALERT_DECODE_ERROR); } #ifdef HITLS_TLS_PROTO_TLCP11 if (pkt->ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { ecdh->ecPara.param.namedcurve = HITLS_EC_GROUP_SM2; } #endif /* HITLS_TLS_PROTO_TLCP11 */ if ((ecdh->ecPara.type == HITLS_EC_CURVE_TYPE_NAMED_CURVE) && (pubKeySize != SAL_CRYPT_GetCryptLength(pkt->ctx, HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN, ecdh->ecPara.param.namedcurve))) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15300, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ecdhe server pubkey length error, curve id = %u, pubkey len = %u.", ecdh->ecPara.param.namedcurve, pubKeySize, 0, 0); return ParseErrorProcess(pkt->ctx, HITLS_PARSE_ECDH_PUBKEY_ERR, 0, NULL, ALERT_ILLEGAL_PARAMETER); } uint8_t *pubKey = NULL; ret = ParseBytesToArray(pkt, &pubKey, pubKeySize); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15299, logStr, ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15301, BINGLOG_STR("pubKey malloc fail."), ALERT_UNKNOWN); } ecdh->pubKey = pubKey; ecdh->pubKeySize = pubKeySize; return HITLS_SUCCESS; } int32_t ParseEcParameters(ParsePacket *pkt, ServerEcdh *ecdh) { const char *logStr = BINGLOG_STR("parse ecdhe curve type fail."); uint8_t curveType = 0; int32_t ret = ParseBytesToUint8(pkt, &curveType); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15292, logStr, ALERT_DECODE_ERROR); } /* In the TLCP, this content can choose not to be sent. */ if (curveType == HITLS_EC_CURVE_TYPE_NAMED_CURVE) { uint16_t namedCurve = 0; ret = ParseBytesToUint16(pkt, &namedCurve); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15291, logStr, ALERT_DECODE_ERROR); } ecdh->ecPara.param.namedcurve = namedCurve; } else { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_UNSUPPORT_KX_CURVE_TYPE, BINLOG_ID15293, BINGLOG_STR("unsupport curve type in server key exchange."), ALERT_ILLEGAL_PARAMETER); } ecdh->ecPara.type = curveType; return HITLS_SUCCESS; } /** * @brief Parse the server ecdh message. * * @param pkt [IN] Context for parsing * @param msg [OUT] Parsed message structure * * @retval HITLS_SUCCESS Parsing succeeded. * @retval HITLS_PARSE_INVALID_MSG_LEN The message length is incorrect. * @retval HITLS_PARSE_UNSUPPORT_KX_CURVE_TYPE Unsupported ECC curve type * @retval HITLS_PARSE_ECDH_PUBKEY_ERR Failed to parse the ECDH public key. * @retval HITLS_PARSE_ECDH_SIGN_ERR Failed to parse the EDH signature. * @retval HITLS_PARSE_GET_SIGN_PARA_ERR Failed to obtain the signature algorithm and hash algorithm. * @retval HITLS_PARSE_VERIFY_SIGN_FAIL Failed to verify the signature. */ static int32_t ParseServerEcdhe(ParsePacket *pkt, ServerKeyExchangeMsg *msg) { TLS_Ctx *ctx = pkt->ctx; /* Parse the EC parameter in the ECDH message on the server */ int32_t ret = ParseEcParameters(pkt, &msg->keyEx.ecdh); if (ret != HITLS_SUCCESS) { return ret; } /* Parse DH public key from peer */ ret = ParseEcdhePublicKey(pkt, &msg->keyEx.ecdh); if (ret != HITLS_SUCCESS) { return ret; } /* ECDHE_PSK and ANON_ECDHE key exchange are not signed */ if (ctx->hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_ECDHE_PSK || ctx->negotiatedInfo.cipherSuiteInfo.authAlg == HITLS_AUTH_NULL) { if (pkt->bufLen != *pkt->bufOffset) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15317, BINGLOG_STR("parse serverkeyEx signature failed."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } uint32_t keyExDataLen = *pkt->bufOffset; uint16_t signAlgorithm = ctx->negotiatedInfo.cipherSuiteInfo.signScheme; if (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11) { ret = ParseSignAlgorithm(pkt, &signAlgorithm); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17015, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ParseSignAlgorithm fail", 0, 0, 0, 0); return ret; } } msg->keyEx.ecdh.signAlgorithm = signAlgorithm; ret = ParseSignature(pkt, &msg->keyEx.ecdh.signSize, &msg->keyEx.ecdh.signData); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_ECDH_SIGN_ERR, BINLOG_ID15318, BINGLOG_STR("parse ecdhe signature fail."), ALERT_UNKNOWN); } ret = VerifySignature(pkt->ctx, pkt->buf, keyExDataLen, msg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17016, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VerifySignature fail", 0, 0, 0, 0); return ret; } ctx->peerInfo.peerSignHashAlg = signAlgorithm; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE /** * @brief Parse the p or g parameter in the DHE kx message. * * @param pkt [IN] Context for parsing * @param paraLen [OUT] Parsed parameter length * @param para [OUT] Parsed parameter * * @return The allocated parameter memory. If the parameter memory is NULL, the parsing fails. */ int32_t ParseDhePara(ParsePacket *pkt, uint16_t *paraLen, uint8_t **para) { int32_t ret = ParseTwoByteLengthField(pkt, paraLen, para); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15294, BINGLOG_STR("dhe para length error."), ALERT_DECODE_ERROR); } else if (ret == HITLS_MEMALLOC_FAIL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID15297, BINGLOG_STR("dhePara malloc fail."), ALERT_UNKNOWN); } if (*paraLen == 0) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15296, BINGLOG_STR("length of dhe para is 0."), ALERT_ILLEGAL_PARAMETER); } return HITLS_SUCCESS; } static int32_t ParseServerDhe(ParsePacket *pkt, ServerKeyExchangeMsg *msg) { ServerDh *dh = &msg->keyEx.dh; const char *logStr = BINGLOG_STR("parse dhe param or PubKey fail. ret %d"); TLS_Ctx *ctx = pkt->ctx; int32_t ret = ParseDhePara(pkt, &dh->plen, &dh->p); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15320, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, logStr, ret, 0, 0, 0); return HITLS_PARSE_DH_P_ERR; } ret = ParseDhePara(pkt, &dh->glen, &dh->g); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15321, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, logStr, ret, 0, 0, 0); return HITLS_PARSE_DH_G_ERR; } /* Parse DH public key from peer */ ret = ParseDhePara(pkt, &dh->pubKeyLen, &dh->pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15322, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, logStr, ret, 0, 0, 0); return HITLS_PARSE_DH_PUBKEY_ERR; } /* DHE_PSK | ANON_DHE key exchange is not signed */ if (ctx->hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_DHE_PSK || ctx->negotiatedInfo.cipherSuiteInfo.authAlg == HITLS_AUTH_NULL) { if (pkt->bufLen != *pkt->bufOffset) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_INVALID_MSG_LEN, BINLOG_ID15323, BINGLOG_STR("parse serverkeyEx signature failed."), ALERT_DECODE_ERROR); } return HITLS_SUCCESS; } uint32_t kxDataLen = *pkt->bufOffset; dh->signAlgorithm = ctx->negotiatedInfo.cipherSuiteInfo.signScheme; ret = ParseSignAlgorithm(pkt, &dh->signAlgorithm); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17017, "ParseSignAlgorithm fail"); } ret = ParseSignature(pkt, &dh->signSize, &dh->signData); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17018, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ParseSignature fail, ret %d", ret, 0, 0, 0); return HITLS_PARSE_DH_SIGN_ERR; } ret = VerifySignature(pkt->ctx, pkt->buf, kxDataLen, msg); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17019, "VerifySignature fail"); } ctx->peerInfo.peerSignHashAlg = dh->signAlgorithm; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_FEATURE_PSK /* In the case of psk negotiation, if ServerKeyExchange is received, the length of the identity hint must be parseed, * but the length may be empty */ static int32_t ParseServerIdentityHint(ParsePacket *pkt, ServerKeyExchangeMsg *msg) { uint16_t identityHintLen = 0; uint8_t *identityHint = NULL; int32_t ret = ParseTwoByteLengthField(pkt, &identityHintLen, &identityHint); if (ret == HITLS_PARSE_INVALID_MSG_LEN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17020, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Parse fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } else if (ret == HITLS_MEMALLOC_FAIL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17021, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Parse fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } if (identityHintLen != 0) { BSL_LOG_BINLOG_VARLEN(BINLOG_ID15324, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "receive server identity hint: %s.", identityHint); } msg->pskIdentityHint = identityHint; msg->hintSize = identityHintLen; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PSK */ #ifdef HITLS_TLS_PROTO_TLCP11 static int32_t VerifyServerKxMsgEcc(ParsePacket *pkt, CERT_SignParam *signParam) { uint8_t *sign = NULL; uint16_t signSize = 0; TLS_Ctx *ctx = pkt->ctx; /* Parse the signature data. The signature data is released after it is used up. The information is not maintained * in the ServerKeyExchangeMsg.keyEx.ecdh file */ int32_t ret = ParseSignature(pkt, &signSize, &sign); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(sign); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16223, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse ecc signature fail.", 0, 0, 0, 0); return HITLS_PARSE_ECDH_SIGN_ERR; } HITLS_CERT_X509 *signCert = SAL_CERT_PairGetX509(ctx->hsCtx->peerCert); HITLS_CERT_Key *pubkey = NULL; ret = SAL_CERT_X509Ctrl(&(ctx->config.tlsConfig), signCert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(sign); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } signParam->sign = sign; signParam->signLen = signSize; ret = SAL_CERT_VerifySign(ctx, pubkey, signParam); SAL_CERT_KeyFree(ctx->config.tlsConfig.certMgrCtx, pubkey); BSL_SAL_FREE(sign); return ret; } /* Signature verification is complete and does not need to be exported to the ServerKeyExchangeMsg structure */ static int32_t ParseServerKxMsgEcc(ParsePacket *pkt) { HITLS_SignAlgo signAlgo; HITLS_HashAlgo hashAlgo; TLS_Ctx *ctx = pkt->ctx; /* The algorithm suite has been determined. The error probability of this function is low. Therefore, the alert is * not required. */ if (!CFG_GetSignParamBySchemes(ctx, ctx->negotiatedInfo.cipherSuiteInfo.signScheme, &signAlgo, &hashAlgo)) { return HITLS_PACK_SIGNATURE_ERR; } uint32_t certLen = 0; uint8_t *cert = SAL_CERT_ClntGmEncodeEncCert(ctx, ctx->hsCtx->peerCert, &certLen); if (cert == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_CERT_ERR_ENCODE, BINLOG_ID16206, BINGLOG_STR("encode encrypt cert failed."), ALERT_INTERNAL_ERROR); } uint32_t signDataLen = 0; uint8_t *signData = HS_PrepareSignDataTlcp(ctx, cert, certLen, &signDataLen); BSL_SAL_FREE(cert); if (signData == NULL) { return ParseErrorProcess(pkt->ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID16207, BINGLOG_STR("data malloc fail."), ALERT_INTERNAL_ERROR); } CERT_SignParam signParam = {signAlgo, hashAlgo, signData, signDataLen, NULL, 0}; int32_t ret = VerifyServerKxMsgEcc(pkt, &signParam); BSL_SAL_FREE(signData); if (ret != HITLS_SUCCESS) { return ParseErrorProcess(pkt->ctx, HITLS_PARSE_VERIFY_SIGN_FAIL, BINLOG_ID16208, BINGLOG_STR("verify signature fail."), ALERT_DECRYPT_ERROR); } return HITLS_SUCCESS; } #endif int32_t ParseServerKeyExchange(TLS_Ctx *ctx, const uint8_t *data, uint32_t len, HS_Msg *hsMsg) { int32_t ret; uint32_t offset = 0u; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; ServerKeyExchangeMsg *msg = &hsMsg->body.serverKeyExchange; msg->keyExType = hsCtx->kxCtx->keyExchAlgo; ParsePacket pkt = {.ctx = ctx, .buf = data, .bufLen = len, .bufOffset = &offset}; (void)pkt; #ifdef HITLS_TLS_FEATURE_PSK if (IsPskNegotiation(ctx)) { if ((ret = ParseServerIdentityHint(&pkt, msg)) != HITLS_SUCCESS) { // log here return ret; } } #endif /* HITLS_TLS_FEATURE_PSK */ switch (hsCtx->kxCtx->keyExchAlgo) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: /** contains the TLCP */ case HITLS_KEY_EXCH_ECDHE_PSK: ret = ParseServerEcdhe(&pkt, msg); break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = ParseServerDhe(&pkt, msg); break; #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_RSA /* PSK & RSA_PSK nego may pack identity hint inside ServerKeyExchange msg */ case HITLS_KEY_EXCH_PSK: case HITLS_KEY_EXCH_RSA_PSK: ret = HITLS_SUCCESS; break; #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: ret = ParseServerKxMsgEcc(&pkt); break; #endif default: ret = HITLS_PARSE_UNSUPPORT_KX_ALG; ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); break; } if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15325, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse serverKeyExMsg fail. keyExchAlgo is %d", hsCtx->kxCtx->keyExchAlgo, 0, 0, 0); } return ret; } void CleanServerKeyExchange(ServerKeyExchangeMsg *msg) { if (msg == NULL) { return; } #ifdef HITLS_TLS_SUITE_KX_ECDHE if (msg->keyExType == HITLS_KEY_EXCH_ECDHE || msg->keyExType == HITLS_KEY_EXCH_ECDHE_PSK) { BSL_SAL_FREE(msg->keyEx.ecdh.pubKey); BSL_SAL_FREE(msg->keyEx.ecdh.signData); } #endif #ifdef HITLS_TLS_SUITE_KX_DHE if (msg->keyExType == HITLS_KEY_EXCH_DHE || msg->keyExType == HITLS_KEY_EXCH_DHE_PSK) { BSL_SAL_FREE(msg->keyEx.dh.p); BSL_SAL_FREE(msg->keyEx.dh.g); BSL_SAL_FREE(msg->keyEx.dh.pubkey); BSL_SAL_FREE(msg->keyEx.dh.signData); } #endif BSL_SAL_FREE(msg->pskIdentityHint); return; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/parse/src/parse_server_key_exchange.c
C
unknown
22,810
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_REASS_H #define HS_REASS_H #include <stdint.h> #include "tls.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Create a message reassembly queue. * * @return Return the header of the linked list. If NULL is returned, memory application fails. */ HS_ReassQueue *HS_ReassNew(void); /** * @brief Release the reassembly message queue. * * @param reass [IN] Reassemble the message queue. */ void HS_ReassFree(HS_ReassQueue *reassQueue); /** * @brief Reassemble a fragmented handshake message. * * @param ctx [IN] TLS object * @param msgInfo [IN] Message structure to be reassembled * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_REASS_INVALID_FRAGMENT An invalid fragment message is received. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_MEMCPY_FAIL Memory Copy Failure */ int32_t HS_ReassAppend(TLS_Ctx *ctx, HS_MsgInfo *msgInfo); /** * @brief Read the complete message of the expected sequence number. * * @param ctx [IN] TLS object * @param msgInfo [OUT] Message structure * @param len [OUT] Message length * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMCPY_FAIL Memory Copy Failure */ int32_t HS_GetReassMsg(TLS_Ctx *ctx, HS_MsgInfo *msgInfo, uint32_t *len); #endif /* end #ifdef HITLS_TLS_PROTO_DTLS12 */ #ifdef __cplusplus } #endif #endif // HS_REASS_H
2301_79861745/bench_create
tls/handshake/reass/include/hs_reass.h
C
unknown
1,945
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_module_list.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hs_common.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_reass.h" #define MAX_NUM_EXCEED_EXPECT 10 static const uint8_t g_startMaskMap[] = { 0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80 }; static const uint8_t g_endMaskMap[] = { 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, 0xFF }; static void SetReassBitMap(uint8_t *reassBitMap, uint32_t fragmentOffset, uint32_t fragmentLength) { /* start indicates the first digit of the flag to be set, and end indicates the last digit of the flag to be set */ uint32_t start = fragmentOffset; uint32_t end = fragmentOffset + fragmentLength - 1; /* When the length is less than 8, the bitmap is set by bit. When the length is greater than or equal to 8, the * bitmap is set in three steps */ if (end - start < 8) { for (uint32_t i = start; i <= end; i++) { /** >>3 indicates divided by 8, & 7 is the remainder 8 */ reassBitMap[(i) >> 3] |= 1 << (i & 7); } } else { uint32_t startOffset = start >> 3; /* bitmap to be set, >> 3 indicates the division by 8 */ uint32_t endOffset = end >> 3; /* last byte of the bitmap to be set, >> 3 is divided by 8 */ /* Assign the first byte, &7 indicates the remainder 8 */ reassBitMap[startOffset] |= g_startMaskMap[start & 7]; /* Assign a value to the middle byte */ uint32_t copyLen = endOffset - startOffset - 1; (void)memset_s(&reassBitMap[startOffset + 1], copyLen, 0xFF, copyLen); /* Assign the last byte, &7 indicates the remainder 8 */ reassBitMap[endOffset] |= g_endMaskMap[end & 7]; } return; } static bool IsReassComplete(const uint8_t *reassBitMap, uint32_t msgLen) { uint32_t i; /* bit map from 0 to (msgLen-1) */ uint32_t maxIndex = msgLen - 1; /* Check the last byte, >> 3 indicates the division by 8, and &7 indicates the remainder by 8 */ if (reassBitMap[maxIndex >> 3] != g_endMaskMap[maxIndex & 7]) { return false; } /* Check the 0th byte to the last 2nd byte, >> 3 is divided by 8 */ for (i = 0; i < (maxIndex >> 3); i++) { if (reassBitMap[i] != 0xFF) { return false; } } return true; } HS_ReassQueue *HS_ReassNew(void) { HS_ReassQueue *reassQueue = (HS_ReassQueue *)BSL_SAL_Calloc(1u, sizeof(HS_ReassQueue)); if (reassQueue == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15751, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "reassQueue malloc fail when new a reassQueue.", 0, 0, 0, 0); return NULL; } LIST_INIT(&reassQueue->head); return reassQueue; } void HS_ReassFree(HS_ReassQueue *reassQueue) { if (reassQueue == NULL) { return; } ListHead *node = NULL; ListHead *tmpNode = NULL; HS_ReassQueue *cur = NULL; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(reassQueue->head)) { cur = LIST_ENTRY(node, HS_ReassQueue, head); LIST_REMOVE(&cur->head); /* Delete the node from the queue. */ BSL_SAL_FREE(cur->reassBitMap); /* Release node content. */ BSL_SAL_FREE(cur->msg); /* Release node content. */ BSL_SAL_FREE(cur); /* Release the node. */ } BSL_SAL_FREE(reassQueue); return; } static HS_ReassQueue *GetReassNode(HS_ReassQueue *reassQueue, uint16_t sequence) { ListHead *node = NULL; ListHead *tmpNode = NULL; HS_ReassQueue *cur = NULL; /* Find the node with the corresponding sequence number in the reassembly queue */ LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(reassQueue->head)) { cur = LIST_ENTRY(node, HS_ReassQueue, head); if (cur->sequence == sequence) { return cur; } } return NULL; } static HS_ReassQueue *ReassNodeNew(HS_ReassQueue *reassQueue, HS_MsgInfo *msgInfo) { HS_ReassQueue *node = (HS_ReassQueue *)BSL_SAL_Calloc(1u, sizeof(HS_ReassQueue)); if (node == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15752, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "node malloc fail when inser a msg to reassQueue.", 0, 0, 0, 0); return NULL; } LIST_INIT(&node->head); if (msgInfo->length != 0) { /* 8 is the number of bits of one byte. The addition of 7 is used to supplement the number of bits. Ensure that * the correct allocated bytes are obtained after each number is divided by 8. */ uint32_t bitMapSize = (msgInfo->length + 7) / 8; node->reassBitMap = BSL_SAL_Calloc(1u, bitMapSize); if (node->reassBitMap == NULL) { BSL_SAL_FREE(node); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15753, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "bitMap malloc fail when inser a msg to reassQueue.", 0, 0, 0, 0); return NULL; } } /* Apply for the space that can be used to cache the entire message */ uint32_t msgLen = DTLS_HS_MSG_HEADER_SIZE + msgInfo->length; node->msg = BSL_SAL_Calloc(1u, msgLen); if (node->msg == NULL) { BSL_SAL_FREE(node->reassBitMap); BSL_SAL_FREE(node); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15754, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "msg malloc fail when inser a msg to reassQueue.", 0, 0, 0, 0); return NULL; } node->type = msgInfo->type; node->sequence = msgInfo->sequence; node->isReassComplete = false; node->msgLen = msgLen; /* Insert a new node */ LIST_ADD_BEFORE(&reassQueue->head, &node->head); return node; } static int32_t ReassembleMsg(TLS_Ctx *ctx, HS_MsgInfo *msgInfo, HS_ReassQueue *node) { /* Check message */ uint32_t bufOffset = DTLS_HS_MSG_HEADER_SIZE + msgInfo->fragmentOffset; if ((node->msgLen < bufOffset) || (node->type != msgInfo->type) || ((node->msgLen - DTLS_HS_MSG_HEADER_SIZE) != msgInfo->length)) { BSL_ERR_PUSH_ERROR(HITLS_REASS_INVALID_FRAGMENT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15755, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "reassemble message fail, fragmentOffset %u; msgType %u, expect %u; msgLen %u", msgInfo->fragmentOffset, msgInfo->type, node->type, msgInfo->length); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15759, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "expect %u", node->msgLen - DTLS_HS_MSG_HEADER_SIZE, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_REASS_INVALID_FRAGMENT; } /* Copy the message header */ if (msgInfo->fragmentOffset == 0u) { if (memcpy_s(&node->msg[0], node->msgLen, &msgInfo->rawMsg[0], DTLS_HS_MSG_HEADER_SIZE) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15756, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "msg header copy fail when append to reassQueue.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMCPY_FAIL; } } if (node->msgLen == DTLS_HS_MSG_HEADER_SIZE) { /* The message is empty and does not need to be reassembled */ node->isReassComplete = true; return HITLS_SUCCESS; } /* Message reassembly */ if (memcpy_s(&node->msg[bufOffset], node->msgLen - bufOffset, &msgInfo->rawMsg[DTLS_HS_MSG_HEADER_SIZE], msgInfo->fragmentLength) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15757, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "msg copy fail when append to reassQueue.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMCPY_FAIL; } /* Set the bitmap and check whether the bitmap is complete */ SetReassBitMap(node->reassBitMap, msgInfo->fragmentOffset, msgInfo->fragmentLength); if (IsReassComplete(node->reassBitMap, node->msgLen - DTLS_HS_MSG_HEADER_SIZE)) { /* Bitmap complete, updated fragment length */ BSL_Uint24ToByte(msgInfo->length, &node->msg[DTLS_HS_FRAGMENT_LEN_ADDR]); node->isReassComplete = true; } return HITLS_SUCCESS; } int32_t HS_ReassAppend(TLS_Ctx *ctx, HS_MsgInfo *msgInfo) { /* If the number of a message exceeds the expected number, discard the message to prevent unlimited memory * application */ if (msgInfo->sequence > ctx->hsCtx->expectRecvSeq + MAX_NUM_EXCEED_EXPECT) { return HITLS_SUCCESS; } HS_ReassQueue *reassQueue = ctx->hsCtx->reassMsg; /* Check whether there are messages in the reassembly queue */ HS_ReassQueue *node = GetReassNode(reassQueue, msgInfo->sequence); if (node == NULL) { /* If no message has the corresponding sequence number, create a new queue node to buffer the message */ node = ReassNodeNew(reassQueue, msgInfo); if (node == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17027, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ReassNodeNew fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } } return ReassembleMsg(ctx, msgInfo, node); } int32_t HS_GetReassMsg(TLS_Ctx *ctx, HS_MsgInfo *msgInfo, uint32_t *len) { /* Check whether there are messages in the reassembly queue */ HS_ReassQueue *node = GetReassNode(ctx->hsCtx->reassMsg, ctx->hsCtx->expectRecvSeq); if (node == NULL) { *len = 0; return HITLS_SUCCESS; } /* If a message exists, check whether the message is complete. If the message is incomplete, return the message and * continue to read the message from the record layer */ if (!node->isReassComplete) { *len = 0; return HITLS_SUCCESS; } /* If the message is a complete message, copy the message */ msgInfo->type = node->type; msgInfo->length = node->msgLen - DTLS_HS_MSG_HEADER_SIZE; msgInfo->sequence = node->sequence; msgInfo->fragmentOffset = 0u; msgInfo->fragmentLength = node->msgLen - DTLS_HS_MSG_HEADER_SIZE; int32_t ret = HS_ReSizeMsgBuf(ctx, node->msgLen); if (ret != HITLS_SUCCESS) { return ret; } if (memcpy_s(ctx->hsCtx->msgBuf, ctx->hsCtx->bufferLen, node->msg, node->msgLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15758, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "msg copy fail when get a msg from reassQueue.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMCPY_FAIL; } msgInfo->rawMsg = ctx->hsCtx->msgBuf; *len = node->msgLen; /* Set the message length. */ LIST_REMOVE(&node->head); /* Delete the node from the queue. */ BSL_SAL_FREE(node->reassBitMap); /* Release node content. */ BSL_SAL_FREE(node->msg); /* Release node content. */ BSL_SAL_FREE(node); /* Release the node. */ return HITLS_SUCCESS; } #endif /* end #ifdef HITLS_TLS_PROTO_DTLS12 */
2301_79861745/bench_create
tls/handshake/reass/src/hs_reass.c
C
unknown
12,138
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 HS_STATE_RECV_H #define HS_STATE_RECV_H #include <stdint.h> #include "tls.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Handshake layer state machine receiving messages processing * * @param ctx [IN] TLS object * * @retval HITLS_SUCCESS * @retval HITLS_MSG_HANDLE_UNSUPPORT_VERSION The TLS version is not supported * @retval For details, see hitls_error.h */ int32_t HS_RecvMsgProcess(TLS_Ctx *ctx); int32_t ReadHsMessage(TLS_Ctx *ctx, uint32_t length); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_STATE_RECV_H */
2301_79861745/bench_create
tls/handshake/recv/include/hs_state_recv.h
C
unknown
1,137
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 RECV_PROCESS_H #define RECV_PROCESS_H #include <stdint.h> #include "tls.h" #include "hs_msg.h" #ifdef __cplusplus extern "C" { #endif int32_t Tls12ServerRecvClientHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg, bool isNeedClientHelloCb); /** * @brief Server processes DTLS client hello message * * @param ctx [IN] TLS context * @param msg [IN] client hello message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsServerRecvClientHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg); #endif /* * @brief Dtls client processes hello verify request message * * @param ctx [IN] TLS context * @param msg [IN] hello verify request message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsClientRecvHelloVerifyRequestProcess(TLS_Ctx *ctx, HS_Msg *msg); #endif /** * @brief Client processes Server Hello message * * @param ctx [IN] TLS context * @param msg [IN] server hello message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t ClientRecvServerHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief Process peer certificate * * @param ctx [IN] TLS context * @param msg [IN] certificate message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t RecvCertificateProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief Process server key exchange * * @param ctx [IN] TLS context * @param msg [IN] server key exchange message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t ClientRecvServerKxProcess(TLS_Ctx *ctx, HS_Msg *msg); /** * @brief Process server certificate request * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t ClientRecvCertRequestProcess(TLS_Ctx *ctx); /** * @brief Process sever hello done * * @param ctx [IN] TLS context * * @return HITLS_SUCCESS */ int32_t ClientRecvServerHelloDoneProcess(TLS_Ctx *ctx); /** * @brief The server processes the client key exchange * * @param ctx [IN] TLS context * @param msg [IN] Parsed handshake message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t ServerRecvClientKxProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief Server process client certificate verification message * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t ServerRecvClientCertVerifyProcess(TLS_Ctx *ctx); /** * @brief TLS1.2 client processes the new session ticket message * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls12ClientRecvNewSeesionTicketProcess(TLS_Ctx *ctx, HS_Msg *hsMsg); /** * @brief TLS1.3 client processes the new session ticket message * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13ClientRecvNewSessionTicketProcess(TLS_Ctx *ctx, HS_Msg *hsMsg); int32_t Tls12ServerRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg); int32_t Tls12ClientRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief Server processes dlts client finished message * * @param ctx [IN] TLS context * @param msg [IN] finished message * * @retval HITLS_SUCCESS * @retval HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL Failed to verify the finished message */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsServerRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg); #endif /** * @brief Client processes dlts server finished message * * @param ctx [IN] TLS context * @param msg [IN] finished message * * @retval HITLS_SUCCESS * @retval HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL Failed to verify the finished message */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsClientRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg); #endif /** * @brief TLS1.3 server process client hello message * * @param ctx [IN] TLS context * @param msg [IN] client hello message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13ServerRecvClientHelloProcess(TLS_Ctx *ctx, HS_Msg *msg); /** * @brief TLS1.3 client process server hello message * * @param ctx [IN] TLS context * @param msg [IN] server hello message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13ClientRecvServerHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief TLS1.3 client process encrypted extensions message * * @param ctx [IN] TLS context * @param msg [IN] encrypted extensions message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13ClientRecvEncryptedExtensionsProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief TLS1.3 client processes certificate request message * * @param ctx [IN] TLS context * @param msg [IN] certificate request message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13ClientRecvCertRequestProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief TLS1.3 process certificate message * * @param ctx [IN] TLS context * @param msg [IN] certificate message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13RecvCertificateProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief TLS1.3 process certificate verify message * * @param ctx [IN] TLS context * @param msg [IN] certificate verify message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13RecvCertVerifyProcess(TLS_Ctx *ctx); /** * @brief TLS1.3 client process finished message * * @param ctx [IN] TLS context * @param msg [IN] finished message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13ClientRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg); /** * @brief TLS1.3 server process finished message * * @param ctx [IN] TLS context * @param msg [IN] finished message * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t Tls13ServerRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg); int32_t ProcessCertCallback(TLS_Ctx *ctx); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end RECV_PROCESS_H */
2301_79861745/bench_create
tls/handshake/recv/include/recv_process.h
C
unknown
7,186
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_build.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "tls_binlog_id.h" #include "bsl_err_internal.h" #include "hitls.h" #include "hitls_error.h" #include "hitls_config.h" #include "tls.h" #include "rec.h" #include "hs.h" #include "hs_msg.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_verify.h" #include "transcript_hash.h" #include "hs_reass.h" #include "parse.h" #include "recv_process.h" #include "bsl_uio.h" #include "hs_kx.h" #include "hs_dtls_timer.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif /* HITLS_TLS_FEATURE_INDICATOR */ #ifdef HITLS_TLS_FEATURE_KEY_UPDATE static int32_t Tls13RecvKeyUpdateProcess(TLS_Ctx *ctx, const HS_Msg *hsMsg) { HITLS_KeyUpdateRequest requestUpdateType = hsMsg->body.keyUpdate.requestUpdate; if ((requestUpdateType != HITLS_UPDATE_NOT_REQUESTED) && (requestUpdateType != HITLS_UPDATE_REQUESTED)) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15354, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "tls1.3 unexpected requestUpdateType(%u)", requestUpdateType, 0, 0, 0); return HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE; } /* Update and activate the app traffic secret used by the local after receiving the key update message */ int32_t ret = HS_TLS13UpdateTrafficSecret(ctx, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15355, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "tls1.3 in key update fail", 0, 0, 0, 0); return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15980, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "tls1.3 recv key update success", 0, 0, 0, 0); if (hsMsg->body.keyUpdate.requestUpdate == HITLS_UPDATE_REQUESTED) { ctx->isKeyUpdateRequest = true; ctx->keyUpdateType = HITLS_UPDATE_NOT_REQUESTED; return HS_ChangeState(ctx, TRY_SEND_KEY_UPDATE); } return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_FEATURE_KEY_UPDATE */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static bool IsUnexpectedHandshaking(const TLS_Ctx *ctx) { return (ctx->state == CM_STATE_HANDSHAKING && ctx->preState == CM_STATE_TRANSPORTING); } static int32_t ProcessHandshakeMsg(TLS_Ctx *ctx, HS_Msg *hsMsg) { uint32_t version = HS_GetVersion(ctx); (void)version; switch (ctx->hsCtx->state) { #ifdef HITLS_TLS_HOST_SERVER case TRY_RECV_CLIENT_HELLO: #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsServerRecvClientHelloProcess(ctx, hsMsg); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS_BASIC return Tls12ServerRecvClientHelloProcess(ctx, hsMsg, true); #else break; #endif /* HITLS_TLS_PROTO_TLS_BASIC only for tls13 */ case TRY_RECV_CERTIFICATE_REQUEST: return ClientRecvCertRequestProcess(ctx); case TRY_RECV_CLIENT_KEY_EXCHANGE: return ServerRecvClientKxProcess(ctx, hsMsg); case TRY_RECV_CERTIFICATE_VERIFY: return ServerRecvClientCertVerifyProcess(ctx); #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_HOST_CLIENT #ifdef HITLS_TLS_PROTO_DTLS12 case TRY_RECV_HELLO_VERIFY_REQUEST: return DtlsClientRecvHelloVerifyRequestProcess(ctx, hsMsg); #endif case TRY_RECV_SERVER_HELLO: return ClientRecvServerHelloProcess(ctx, hsMsg); case TRY_RECV_SERVER_KEY_EXCHANGE: return ClientRecvServerKxProcess(ctx, hsMsg); case TRY_RECV_SERVER_HELLO_DONE: return ClientRecvServerHelloDoneProcess(ctx); #ifdef HITLS_TLS_FEATURE_SESSION_TICKET case TRY_RECV_NEW_SESSION_TICKET: return Tls12ClientRecvNewSeesionTicketProcess(ctx, hsMsg); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #endif /* HITLS_TLS_HOST_CLIENT */ case TRY_RECV_CERTIFICATE: return RecvCertificateProcess(ctx, hsMsg); case TRY_RECV_FINISH: #ifdef HITLS_TLS_HOST_CLIENT if (ctx->isClient) { #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsClientRecvFinishedProcess(ctx, hsMsg); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS_BASIC return Tls12ClientRecvFinishedProcess(ctx, hsMsg); #endif /* HITLS_TLS_PROTO_TLS_BASIC */ } #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsServerRecvFinishedProcess(ctx, hsMsg); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS_BASIC return Tls12ServerRecvFinishedProcess(ctx, hsMsg); #else break; #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #endif /* HITLS_TLS_HOST_SERVER */ default: break; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_STATE_ILLEGAL); BSL_LOG_BINLOG_VARLEN(BINLOG_ID15350, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Handshake state error: should recv msg, but current state is %s.", HS_GetStateStr(ctx->hsCtx->state)); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_STATE_ILLEGAL; } static int32_t ProcessReceivedHandshakeMsg(TLS_Ctx *ctx, HS_Msg *hsMsg) { if (hsMsg->type == HELLO_REQUEST) { if (ctx->hsCtx->state == TRY_RECV_HELLO_REQUEST) { ctx->negotiatedInfo.isRenegotiation = true; /* Start renegotiation */ ctx->negotiatedInfo.renegotiationNum++; return HS_ChangeState(ctx, TRY_SEND_CLIENT_HELLO); } /* The HelloRequest message should be ignored during the handshake. */ return HITLS_SUCCESS; } if (hsMsg->type == CLIENT_HELLO && IsUnexpectedHandshaking(ctx)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17028, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "refuse Renegotiation request from client", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_WARNING, ALERT_NO_RENEGOTIATION); (void)HS_ChangeState(ctx, TLS_CONNECTED); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } return ProcessHandshakeMsg(ctx, hsMsg); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13ProcessReceivedHandshakeMsg(TLS_Ctx *ctx, HS_Msg *hsMsg) { if ((hsMsg->type == HELLO_REQUEST) && (ctx->isClient)) { /* The HelloRequest message should be ignored during the handshake. */ return HITLS_SUCCESS; } switch (ctx->hsCtx->state) { #ifdef HITLS_TLS_HOST_SERVER case TRY_RECV_CLIENT_HELLO: return Tls13ServerRecvClientHelloProcess(ctx, hsMsg); #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_HOST_CLIENT case TRY_RECV_CERTIFICATE_REQUEST: return Tls13ClientRecvCertRequestProcess(ctx, hsMsg); case TRY_RECV_SERVER_HELLO: return Tls13ClientRecvServerHelloProcess(ctx, hsMsg); case TRY_RECV_ENCRYPTED_EXTENSIONS: return Tls13ClientRecvEncryptedExtensionsProcess(ctx, hsMsg); #endif /* HITLS_TLS_HOST_CLIENT */ case TRY_RECV_CERTIFICATE: return Tls13RecvCertificateProcess(ctx, hsMsg); case TRY_RECV_CERTIFICATE_VERIFY: return Tls13RecvCertVerifyProcess(ctx); case TRY_RECV_FINISH: #ifdef HITLS_TLS_HOST_CLIENT if (ctx->isClient) { return Tls13ClientRecvFinishedProcess(ctx, hsMsg); } #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER return Tls13ServerRecvFinishedProcess(ctx, hsMsg); #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_FEATURE_KEY_UPDATE case TRY_RECV_KEY_UPDATE: return Tls13RecvKeyUpdateProcess(ctx, hsMsg); #endif case TRY_RECV_NEW_SESSION_TICKET: return Tls13ClientRecvNewSessionTicketProcess(ctx, hsMsg); default: break; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_STATE_ILLEGAL); BSL_LOG_BINLOG_VARLEN(BINLOG_ID15343, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "tls1.3 handshake state error: should recv msg, but current state is %s.", HS_GetStateStr(ctx->hsCtx->state)); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_STATE_ILLEGAL; } #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t ReadHsMessage(TLS_Ctx *ctx, uint32_t length) { HS_Ctx *hsCtx = ctx->hsCtx; if (hsCtx == NULL || hsCtx->msgBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17029, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_NULL_INPUT; } if (hsCtx->msgLen >= length) { return HITLS_SUCCESS; } int32_t ret = HS_GrowMsgBuf(ctx, length, true); if (ret != HITLS_SUCCESS) { return ret; } uint32_t readLen = 0; do { readLen = 0; ret = REC_Read(ctx, REC_TYPE_HANDSHAKE, &hsCtx->msgBuf[hsCtx->msgLen], &readLen, length - hsCtx->msgLen); hsCtx->msgLen += readLen; if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { break; } } while (ret == HITLS_SUCCESS && hsCtx->msgLen < length && readLen != 0); if (ret == HITLS_SUCCESS && hsCtx->msgLen < length) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } return ret; } #ifdef HITLS_TLS_PROTO_TLS static int32_t ReadThenParseTlsHsMsg(TLS_Ctx *ctx, HS_Msg *hsMsg) { HS_Ctx *hsCtx = ctx->hsCtx; int32_t ret = ReadHsMessage(ctx, HS_MSG_HEADER_SIZE); if (ret != HITLS_SUCCESS) { return ret; } HS_MsgInfo hsMsgInfo = {0}; ret = HS_ParseMsgHeader(ctx, hsCtx->msgBuf, HS_MSG_HEADER_SIZE, &hsMsgInfo); if (ret != HITLS_SUCCESS) { return ret; } ret = ReadHsMessage(ctx, hsMsgInfo.headerAndBodyLen); // hsCtx->msgBuf always has enough buf if (ret != HITLS_SUCCESS) { return ret; } ret = HS_ParseMsg(ctx, &hsMsgInfo, hsMsg); if (ret != HITLS_SUCCESS) { return ret; } /* The HelloRequest message is not included. */ if (hsMsgInfo.type != HELLO_REQUEST && hsMsgInfo.type != KEY_UPDATE && !(HS_GetVersion(ctx) == HITLS_VERSION_TLS13 && hsMsgInfo.type == NEW_SESSION_TICKET)) { /* Session hash is needed to compute ems, the VERIFY_Append must be dealt with beforehand */ ret = VERIFY_Append(hsCtx->verifyCtx, hsCtx->msgBuf, hsMsgInfo.headerAndBodyLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17031, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VERIFY_Append fail", 0, 0, 0, 0); HS_CleanMsg(hsMsg); return ret; } } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, HS_GetVersion(ctx), REC_TYPE_HANDSHAKE, hsMsgInfo.rawMsg, hsMsgInfo.length, ctx, ctx->config.tlsConfig.msgArg); #endif /* HITLS_TLS_FEATURE_INDICATOR */ hsCtx->msgLen = 0; return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS_BASIC static int32_t Tls12TryRecvHandShakeMsg(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Msg hsMsg = {0}; (void)memset_s(&hsMsg, sizeof(HS_Msg), 0, sizeof(HS_Msg)); if (ctx->hsCtx->hsMsg == NULL) { ret = ReadThenParseTlsHsMsg(ctx, &hsMsg); if (ret != HITLS_SUCCESS) { HS_CleanMsg(&hsMsg); return ret; } ctx->hsCtx->hsMsg = &hsMsg; ctx->hsCtx->readSubState = TLS_PROCESS_STATE_A; } ret = ProcessReceivedHandshakeMsg(ctx, ctx->hsCtx->hsMsg); if (ret == HITLS_SUCCESS) { HS_CleanMsg(ctx->hsCtx->hsMsg); if (ctx->hsCtx->hsMsg != &hsMsg) { BSL_SAL_FREE(ctx->hsCtx->hsMsg); } ctx->hsCtx->hsMsg = NULL; } if (ctx->hsCtx->hsMsg == &hsMsg) { ctx->hsCtx->hsMsg = BSL_SAL_Dump(&hsMsg, sizeof(HS_Msg)); if (ctx->hsCtx->hsMsg == NULL) { HS_CleanMsg(&hsMsg); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17357, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "hsMsg dump fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } } return ret; } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13TryRecvHandShakeMsg(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Msg hsMsg = {0}; (void)memset_s(&hsMsg, sizeof(HS_Msg), 0, sizeof(HS_Msg)); if (ctx->hsCtx->hsMsg == NULL) { ret = ReadThenParseTlsHsMsg(ctx, &hsMsg); if (ret != HITLS_SUCCESS) { HS_CleanMsg(&hsMsg); return ret; } ctx->hsCtx->hsMsg = &hsMsg; ctx->hsCtx->readSubState = TLS_PROCESS_STATE_A; } ret = Tls13ProcessReceivedHandshakeMsg(ctx, ctx->hsCtx->hsMsg); if (ret == HITLS_SUCCESS) { HS_CleanMsg(ctx->hsCtx->hsMsg); if (ctx->hsCtx->hsMsg != &hsMsg) { BSL_SAL_FREE(ctx->hsCtx->hsMsg); } ctx->hsCtx->hsMsg = NULL; } if (ctx->hsCtx->hsMsg == &hsMsg) { ctx->hsCtx->hsMsg = BSL_SAL_Dump(&hsMsg, sizeof(HS_Msg)); if (ctx->hsCtx->hsMsg == NULL) { HS_CleanMsg(&hsMsg); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17358, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "hsMsg dump fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } } return ret; } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_PROTO_TLS */ #ifdef HITLS_TLS_PROTO_DTLS12 static int32_t DtlsCheckTimeoutAndProcess(TLS_Ctx *ctx, int32_t retValue) { (void)ctx; #ifdef HITLS_BSL_UIO_UDP int32_t ret = HITLS_DtlsProcessTimeout(ctx); if (ret != HITLS_SUCCESS && ret != HITLS_MSG_HANDLE_DTLS_RETRANSMIT_NOT_TIMEOUT) { return ret; } #endif /* HITLS_REC_NORMAL_RECV_BUF_EMPTY is returned here, and the choice is given to the user instead of the next read, * Prevents users from waiting for a long time due to long timeout. */ return retValue; } int32_t DtlsDisorderMsgProcess(TLS_Ctx *ctx, HS_MsgInfo *hsMsgInfo) { HS_Ctx *hsCtx = ctx->hsCtx; /* The SCTP scenario must be sequenced. */ if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNMATCHED_SEQUENCE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15351, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "msg with unmatched sequence, recv %u, expect %u.", hsMsgInfo->sequence, hsCtx->expectRecvSeq, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_MSG_HANDLE_UNMATCHED_SEQUENCE; } #ifdef HITLS_BSL_UIO_UDP /* In the renegotiation state, the FINISHED message of the previous handshake should be discarded. */ if (ctx->hsCtx->expectRecvSeq == 0 && hsMsgInfo->type == FINISHED) { return HITLS_SUCCESS; } /* If the sequence number of the received message is greater than expected, the message is cached in the reassembly * queue. */ if (hsMsgInfo->sequence > ctx->hsCtx->expectRecvSeq) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17033, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the message is need to cache in the reassembly queue", 0, 0, 0, 0); return HS_ReassAppend(ctx, hsMsgInfo); } return HITLS_SUCCESS; #else BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17034, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; #endif /* HITLS_BSL_UIO_UDP */ } static int32_t DtlsCheckAndParseMsg(TLS_Ctx *ctx, HS_MsgInfo *hsMsgInfo, HS_Msg *hsMsg) { HS_Ctx *hsCtx = ctx->hsCtx; int32_t ret = CheckHsMsgType(ctx, hsMsgInfo->type); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_ParseMsg(ctx, hsMsgInfo, hsMsg); if (ret != HITLS_SUCCESS) { HS_CleanMsg(hsMsg); return ret; } hsCtx->expectRecvSeq++; /* Auto-increment of the received message sequence number */ return ret; } static int32_t ReadDtlsHsMessage(TLS_Ctx *ctx, HS_MsgInfo *hsMsgInfo) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; if (hsCtx == NULL || hsCtx->msgBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17035, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_NULL_INPUT; } uint8_t *buf = &hsCtx->msgBuf[hsCtx->msgLen]; uint32_t readLen = 0; if (hsCtx->msgLen < DTLS_HS_MSG_HEADER_SIZE) { ret = REC_Read(ctx, REC_TYPE_HANDSHAKE, buf, &readLen, (uint32_t)(DTLS_HS_MSG_HEADER_SIZE - hsCtx->msgLen)); if (ret != HITLS_SUCCESS) { if (ret != HITLS_REC_NORMAL_RECV_BUF_EMPTY) { return ret; } if (hsCtx->msgLen == 0) { return DtlsCheckTimeoutAndProcess(ctx, ret); } } hsCtx->msgLen += readLen; } ret = HS_ParseMsgHeader(ctx, hsCtx->msgBuf, hsCtx->msgLen, hsMsgInfo); if (ret != HITLS_SUCCESS) { return ret; } ret = ReadHsMessage(ctx, hsMsgInfo->fragmentLength + DTLS_HS_MSG_HEADER_SIZE); if ((hsMsgInfo->fragmentLength + DTLS_HS_MSG_HEADER_SIZE) != hsCtx->msgLen || ret != HITLS_SUCCESS) { hsCtx->msgLen = 0; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15600, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DTLS handshake msg length error, need to alert.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_PARSE_INVALID_MSG_LEN; } return ret; } static int32_t DtlsReadAndParseHandshakeMsg(TLS_Ctx *ctx, HS_Msg *hsMsg) { HS_MsgInfo hsMsgInfo = {0}; uint32_t dataLen = 0; int32_t ret = HS_GetReassMsg(ctx, &hsMsgInfo, &dataLen); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *buf = ctx->hsCtx->msgBuf; if (dataLen == 0) { ret = ReadDtlsHsMessage(ctx, &hsMsgInfo); if (ret != HITLS_SUCCESS) { return ret; } buf = ctx->hsCtx->msgBuf; dataLen = ctx->hsCtx->msgLen; ctx->hsCtx->msgLen = 0; /* when the hello verify request is lost and a clienthello with 0 message sequence is received again, the expect sequence is reset and dealt with same as receiving it for the first time. */ if (hsMsgInfo.sequence == 0 && ctx->hsCtx->expectRecvSeq == 1 && ctx->hsCtx->state == TRY_RECV_CLIENT_HELLO && hsMsgInfo.type == CLIENT_HELLO && !IsUnexpectedHandshaking(ctx) && ctx->state == CM_STATE_HANDSHAKING && !BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { ctx->hsCtx->expectRecvSeq = 0; ctx->hsCtx->nextSendSeq = 0; } /* SCTP messages are not out of order. Therefore, an alert message must be sent for the out-of-order messages */ if (hsMsgInfo.sequence != ctx->hsCtx->expectRecvSeq && !IsUnexpectedHandshaking(ctx)) { return DtlsDisorderMsgProcess(ctx, &hsMsgInfo); } /* If the message is fragmented, the message needs to be reassembled. */ if (hsMsgInfo.fragmentLength != hsMsgInfo.length) { return HS_ReassAppend(ctx, &hsMsgInfo); } } ret = DtlsCheckAndParseMsg(ctx, &hsMsgInfo, hsMsg); if (ret != HITLS_SUCCESS) { return ret; } /* The HelloRequest message is not included. */ if (hsMsgInfo.type != HELLO_REQUEST) { /* Session hash is needed to compute ems, the VERIFY_Append must be dealt with beforehand */ ret = VERIFY_Append(ctx->hsCtx->verifyCtx, buf, dataLen); if (ret != HITLS_SUCCESS) { HS_CleanMsg(hsMsg); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17036, "VERIFY_Append fail"); } } ctx->hsCtx->hsMsg = hsMsg; #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, HS_GetVersion(ctx), REC_TYPE_HANDSHAKE, hsMsgInfo.rawMsg, hsMsgInfo.length, ctx, ctx->config.tlsConfig.msgArg); #endif /* HITLS_TLS_FEATURE_INDICATOR */ return HITLS_SUCCESS; } static int32_t DtlsTryRecvHandShakeMsg(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Msg hsMsg = {0}; (void)memset_s(&hsMsg, sizeof(HS_Msg), 0, sizeof(HS_Msg)); if (ctx->hsCtx->hsMsg == NULL) { ret = DtlsReadAndParseHandshakeMsg(ctx, &hsMsg); if (ret != HITLS_SUCCESS || ctx->hsCtx->hsMsg == NULL) { return ret; } ctx->hsCtx->readSubState = TLS_PROCESS_STATE_A; } ret = ProcessReceivedHandshakeMsg(ctx, ctx->hsCtx->hsMsg); if (ret == HITLS_SUCCESS) { HS_CleanMsg(ctx->hsCtx->hsMsg); if (ctx->hsCtx->hsMsg != &hsMsg) { BSL_SAL_FREE(ctx->hsCtx->hsMsg); } ctx->hsCtx->hsMsg = NULL; } if (ctx->hsCtx->hsMsg == &hsMsg) { ctx->hsCtx->hsMsg = BSL_SAL_Dump(&hsMsg, sizeof(HS_Msg)); if (ctx->hsCtx->hsMsg == NULL) { HS_CleanMsg(&hsMsg); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17359, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "hsMsg dump fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } } return ret; } #endif int32_t HandleResult(TLS_Ctx *ctx, int32_t ret) { if (ret != HITLS_SUCCESS) { if (ctx->method.getAlertFlag(ctx)) { /* The alert has been processed. The handshake should be terminated. */ return ret; } if (ret == HITLS_REC_NORMAL_RECV_DISORDER_MSG) { /* App messages and finished messages are out of order. The handshake proceeds. */ return HITLS_SUCCESS; } if ((ret == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG) && REC_GetUnexpectedMsgType(ctx) == REC_TYPE_CHANGE_CIPHER_SPEC) { /* The CCS message is received. The handshake proceeds. */ return HITLS_SUCCESS; } /* Other errors are returned */ } return ret; } int32_t HS_RecvMsgProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_FLIGHT /* If isFlightTransmitEnable is enabled, the handshake information stored in the bUio needs to be sent when the * receiving status is changed. */ if (ctx->config.tlsConfig.isFlightTransmitEnable) { ret = REC_FlightTransmit(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_FLIGHT */ uint32_t version = HS_GetVersion(ctx); switch (version) { #ifdef HITLS_TLS_PROTO_TLS case HITLS_VERSION_TLS12: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_VERSION_TLCP_DTLCP11: #if defined(HITLS_TLS_PROTO_DTLS12) if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { ret = DtlsTryRecvHandShakeMsg(ctx); break; } #endif #endif /* HITLS_TLS_PROTO_TLCP11 */ #ifdef HITLS_TLS_PROTO_TLS_BASIC ret = Tls12TryRecvHandShakeMsg(ctx); break; #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 case HITLS_VERSION_TLS13: ret = Tls13TryRecvHandShakeMsg(ctx); break; #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_PROTO_TLS */ #ifdef HITLS_TLS_PROTO_DTLS12 case HITLS_VERSION_DTLS12: ret = DtlsTryRecvHandShakeMsg(ctx); break; #endif default: BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15352, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Handshake state recv error: unsupport TLS version.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } return HandleResult(ctx, ret); }
2301_79861745/bench_create
tls/handshake/recv/src/hs_state_recv.c
C
unknown
24,736
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #include <stdint.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_log.h" #include "bsl_bytes.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "tls.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_common.h" #include "hs_extensions.h" #include "hitls_error.h" #include "tls_binlog_id.h" #include "cert_mgr_ctx.h" #include "recv_process.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) // The client processes the certificate request int32_t ClientRecvCertRequestProcess(TLS_Ctx *ctx) { /** * If the server certificate is not received, a failure message is returned after the cert request is received * RFC 5246 7.4.4: Note: It is a fatal handshake_failure alert for * an anonymous server to request client authentication. */ #ifdef HITLS_TLS_FEATURE_CERT_CB int32_t ret = ProcessCertCallback(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CERT_CB */ if (ctx->hsCtx->peerCert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15869, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "got cert request but not get peer certificate.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE; } /* If ECC and ECHDE of TLCP are used, this parameter must be set because the * TLCP server must send the req cert message to the client to send the certificate, which may be * used for identity authentication, The latter may be used for key derivation, depending on the cipher suite and * server configuration (isSupportClientVerify). */ ctx->hsCtx->isNeedClientCert = true; CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CERT_TYPE_UNKNOWN; expectCertInfo.signSchemeList = ctx->peerInfo.signatureAlgorithms; expectCertInfo.signSchemeNum = ctx->peerInfo.signatureAlgorithmsSize; expectCertInfo.caList = ctx->peerInfo.caList; (void)SAL_CERT_SelectCertByInfo(ctx, &expectCertInfo); return HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO_DONE); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_FEATURE_PHA static int32_t Tls13ClientStoreCertReqCtx(TLS_Ctx *ctx, const CertificateRequestMsg *certReq) { /** If authentication is not performed after handshake, the cert req ctx length should be 0 */ if ((ctx->phaState != PHA_REQUESTED && certReq->certificateReqCtxSize != 0) || (ctx->phaState == PHA_REQUESTED && certReq->certificateReqCtxSize == 0)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15870, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certificateReqCtxSize is invalid.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX; } if (certReq->certificateReqCtxSize != 0) { BSL_SAL_FREE(ctx->certificateReqCtx); ctx->certificateReqCtx = BSL_SAL_Calloc(certReq->certificateReqCtxSize, sizeof(uint8_t)); if (ctx->certificateReqCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17039, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ctx->certificateReqCtxSize = certReq->certificateReqCtxSize; int32_t ret = memcpy_s(ctx->certificateReqCtx, certReq->certificateReqCtxSize, certReq->certificateReqCtx, certReq->certificateReqCtxSize); if (ret != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16171, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "client calloc cert req ctx failed.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PHA */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13ClientPreProcessCertRequest(TLS_Ctx *ctx, const CertificateRequestMsg *certReq) { int32_t ret = HS_CheckReceivedExtension( ctx, CERTIFICATE_REQUEST, certReq->extensionTypeMask, HS_EX_TYPE_TLS1_3_ALLOWED_OF_CERTIFICATE_REQUEST); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_PHA ret = Tls13ClientStoreCertReqCtx(ctx, certReq); if (ret != HITLS_SUCCESS) { return ret; } #else if (certReq->certificateReqCtxSize != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15729, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certificateReqCtxSize is invalid.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX; } #endif /* HITLS_TLS_FEATURE_PHA */ ctx->hsCtx->isNeedClientCert = true; if (certReq->signatureAlgorithms == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17040, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "miss signatureAlgorithms extension", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_MISSING_EXTENSION); return HITLS_MSG_HANDLE_MISSING_EXTENSION; } return HITLS_SUCCESS; } int32_t Tls13ClientRecvCertRequestProcess(TLS_Ctx *ctx, const HS_Msg *msg) { const CertificateRequestMsg *certReq = &msg->body.certificateReq; int32_t ret = HITLS_SUCCESS; if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_A) { ret = Tls13ClientPreProcessCertRequest(ctx, certReq); if (ret != HITLS_SUCCESS) { return ret; } ctx->hsCtx->readSubState = TLS_PROCESS_STATE_B; } #ifdef HITLS_TLS_FEATURE_PHA if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_B) { if (ctx->phaState == PHA_REQUESTED) { #ifdef HITLS_TLS_FEATURE_CERT_CB ret = ProcessCertCallback(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CERT_CB */ CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CERT_TYPE_UNKNOWN; expectCertInfo.signSchemeList = ctx->peerInfo.signatureAlgorithms; expectCertInfo.signSchemeNum = ctx->peerInfo.signatureAlgorithmsSize; expectCertInfo.caList = ctx->peerInfo.caList; (void)SAL_CERT_SelectCertByInfo(ctx, &expectCertInfo); } } if (ctx->phaState == PHA_REQUESTED) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE); } #endif /* HITLS_TLS_FEATURE_PHA */ return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/recv/src/recv_cert_request.c
C
unknown
7,280
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER) || defined(HITLS_TLS_PROTO_TLS13) #include <stdint.h> #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_verify.h" #include "hs_common.h" #include "hs_msg.h" #include "recv_process.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t ServerRecvClientCertVerifyProcess(TLS_Ctx *ctx) { int32_t ret; ret = VERIFY_CalcVerifyData(ctx, true, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15871, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server Calculate client finished data error.", 0, 0, 0, 0); (void)memset_s(ctx->hsCtx->masterKey, sizeof(ctx->hsCtx->masterKey), 0, sizeof(ctx->hsCtx->masterKey)); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13RecvCertVerifyProcess(TLS_Ctx *ctx) { int32_t ret; if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_A) { /* The signature verification has been completed in the parser part. Only the finish data of the peer needs to be calculated. */ ret = VERIFY_Tls13CalcVerifyData(ctx, !ctx->isClient); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15872, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "calculate finished data fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ctx->hsCtx->readSubState = TLS_PROCESS_STATE_B; } if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_B) { if (ctx->isClient && ctx->hsCtx->isNeedClientCert) { #ifdef HITLS_TLS_FEATURE_CERT_CB ret = ProcessCertCallback(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CERT_CB */ CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CERT_TYPE_UNKNOWN; expectCertInfo.signSchemeList = ctx->peerInfo.signatureAlgorithms; expectCertInfo.signSchemeNum = ctx->peerInfo.signatureAlgorithmsSize; expectCertInfo.caList = ctx->peerInfo.caList; (void)SAL_CERT_SelectCertByInfo(ctx, &expectCertInfo); } } return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER || HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/recv/src/recv_cert_verify.c
C
unknown
3,442
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <string.h> #include "hitls_build.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 "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_verify.h" #include "hs_msg.h" #include "hs_extensions.h" #include "alert.h" static const int32_t X509_ERR_ALERT_MAP[] = { [(HITLS_X509_V_ERR_UNSPECIFIED - 1) & 0XFF] = ALERT_INTERNAL_ERROR, [(HITLS_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_UNABLE_TO_GET_CRL - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_CERT_SIGNATURE_FAILURE - 1) & 0XFF] = ALERT_DECRYPT_ERROR, [(HITLS_X509_V_ERR_CRL_SIGNATURE_FAILURE - 1) & 0XFF] = ALERT_DECRYPT_ERROR, [(HITLS_X509_V_ERR_CERT_NOT_YET_VALID - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_CERT_HAS_EXPIRED - 1) & 0XFF] = ALERT_CERTIFICATE_EXPIRED, [(HITLS_X509_V_ERR_CRL_NOT_YET_VALID - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_CRL_HAS_EXPIRED - 1) & 0XFF] = ALERT_CERTIFICATE_EXPIRED, [(HITLS_X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_OUT_OF_MEM - 1) & 0XFF] = ALERT_INTERNAL_ERROR, [(HITLS_X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_CERT_CHAIN_TOO_LONG - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_CERT_REVOKED - 1) & 0XFF] = ALERT_CERTIFICATE_REVOKED, [(HITLS_X509_V_ERR_INVALID_CA - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_PATH_LENGTH_EXCEEDED - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_INVALID_PURPOSE - 1) & 0XFF] = ALERT_UNSUPPORTED_CERTIFICATE, [(HITLS_X509_V_ERR_CERT_UNTRUSTED - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_CERT_REJECTED - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_SUBJECT_ISSUER_MISMATCH - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_AKID_SKID_MISMATCH - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_KEYUSAGE_NO_CERTSIGN - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER - 1) & 0XFF] = ALERT_UNKNOWN_CA, [(HITLS_X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_KEYUSAGE_NO_CRL_SIGN - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_INVALID_NON_CA - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_INVALID_EXTENSION - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_INVALID_POLICY_EXTENSION - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_NO_EXPLICIT_POLICY - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_DIFFERENT_CRL_SCOPE - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_ERROR_IN_CMP_CERT_NOT_AFTER_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_ERROR_IN_CMP_CRL_THIS_UPDATE_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_ERROR_IN_CMP_CRL_NEXT_UPDATE_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_ERROR_IN_CMP_CERT_NOT_BEFORE_FIELD - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, [(HITLS_X509_V_ERR_CRL_PATH_VALIDATION_ERROR - 1) & 0XFF] = ALERT_BAD_CERTIFICATE, }; ALERT_Description GetAlertfromX509Err(HITLS_ERROR x509err) { uint32_t size = sizeof(X509_ERR_ALERT_MAP) / sizeof(X509_ERR_ALERT_MAP[0]); uint32_t index = ((uint32_t)x509err - 1) & 0XFF; if (index < size) { return X509_ERR_ALERT_MAP[index]; } return ALERT_BAD_CERTIFICATE; } int32_t ClientCheckPeerCert(TLS_Ctx *ctx, HITLS_CERT_X509 *cert) { CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CFG_GetCertTypeByCipherSuite(ctx->negotiatedInfo.cipherSuiteInfo.cipherSuite); expectCertInfo.signSchemeList = ctx->config.tlsConfig.signAlgorithms; expectCertInfo.signSchemeNum = ctx->config.tlsConfig.signAlgorithmsSize; if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { expectCertInfo.ellipticCurveList = ctx->config.tlsConfig.groups; expectCertInfo.ellipticCurveNum = ctx->config.tlsConfig.groupsSize; } expectCertInfo.ecPointFormatList = ctx->config.tlsConfig.pointFormats; expectCertInfo.ecPointFormatNum = ctx->config.tlsConfig.pointFormatsSize; return SAL_CERT_CheckCertInfo(ctx, &expectCertInfo, cert, false, true); } int32_t ServerCheckPeerCert(TLS_Ctx *ctx, HITLS_CERT_X509 *cert) { CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CERT_TYPE_UNKNOWN; expectCertInfo.signSchemeList = ctx->config.tlsConfig.signAlgorithms; expectCertInfo.signSchemeNum = ctx->config.tlsConfig.signAlgorithmsSize; return SAL_CERT_CheckCertInfo(ctx, &expectCertInfo, cert, false, true); } static int32_t ClientCheckCert(TLS_Ctx *ctx, CERT_Pair *peerCert) { int32_t ret; ret = ClientCheckPeerCert(ctx, SAL_CERT_PairGetX509(peerCert)); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16224, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client check peer cert failed", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_PROTO_TLCP11 /* The encryption certificate is required for TLS of TLCP. Both ECDHE and ECC of the client depend on the encryption * certificate. */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { HITLS_CERT_Key *cert = SAL_CERT_GetTlcpEncCert(peerCert); if (cert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16225, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client check peer enc cert failed.", 0, 0, 0, 0); return HITLS_CERT_ERR_EXP_CERT; } /* The encryption certificate only needs to ensure that the certificate type matches the TLCP. * That is, the encryption public key type matches the negotiation cipher suite. */ CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CFG_GetCertTypeByCipherSuite(ctx->negotiatedInfo.cipherSuiteInfo.cipherSuite); ret = SAL_CERT_CheckCertInfo(ctx, &expectCertInfo, cert, false, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17041, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckCertInfo fail, ret = %d.", ret, 0, 0, 0); } } #endif return ret; } static int32_t ServerCheckCert(TLS_Ctx *ctx, CERT_Pair *peerCert) { int32_t ret; ret = ServerCheckPeerCert(ctx, SAL_CERT_PairGetX509(peerCert)); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16226, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server check peer cert failed.", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_PROTO_TLCP11 /* Service processing logic. The ECDHE exchange algorithm logic requires the encryption certificate */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11 && ctx->negotiatedInfo.cipherSuiteInfo.kxAlg == HITLS_KEY_EXCH_ECDHE) { HITLS_CERT_Key *cert = SAL_CERT_GetTlcpEncCert(peerCert); if (cert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16227, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "service check peer enc cert failed", 0, 0, 0, 0); return HITLS_CERT_ERR_EXP_CERT; } /* The encryption certificate only needs to ensure that the certificate type matches the TLCP. * That is, the encryption public key type matches the negotiation cipher suite. */ CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CFG_GetCertTypeByCipherSuite(ctx->negotiatedInfo.cipherSuiteInfo.cipherSuite); ret = SAL_CERT_CheckCertInfo(ctx, &expectCertInfo, cert, false, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17042, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckCertInfo fail, ret = %d.", ret, 0, 0, 0); } } #endif return ret; } #ifdef HITLS_TLS_CONFIG_KEY_USAGE static bool CheckCertKeyUsage(TLS_Ctx *ctx, CERT_Pair *peerCert) { bool checkUsageRec = false; HITLS_CERT_X509 *cert = SAL_CERT_PairGetX509(peerCert); if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { return SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE); } HITLS_KeyExchAlgo kxAlg = ctx->negotiatedInfo.cipherSuiteInfo.kxAlg; if (ctx->isClient) { switch (kxAlg) { case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_ECDHE: case HITLS_KEY_EXCH_ECDHE_PSK: case HITLS_KEY_EXCH_DHE_PSK: checkUsageRec = SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE); break; case HITLS_KEY_EXCH_RSA: case HITLS_KEY_EXCH_ECC: case HITLS_KEY_EXCH_RSA_PSK: checkUsageRec = SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_KEYENC_USAGE); break; case HITLS_KEY_EXCH_ECDH: case HITLS_KEY_EXCH_DH: checkUsageRec = SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_KEY_AGREEMENT_USAGE); break; default: break; } } else { switch (kxAlg) { case HITLS_KEY_EXCH_ECDH: case HITLS_KEY_EXCH_DH: checkUsageRec = SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_KEY_AGREEMENT_USAGE); break; default: checkUsageRec = SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE); break; } } return checkUsageRec; } #endif /* HITLS_TLS_CONFIG_KEY_USAGE */ /** * @brief Process the peer certificate, check, and save it. * * @param ctx [IN/OUT] TLS context * @param certs [IN] Certificate message * * @retval HITLS_SUCCESS succeeded. * @retval For other error codes, see hitls_error.h. */ static int32_t ProcessPeerCertificate(TLS_Ctx *ctx, const CertificateMsg *certs) { int32_t ret; CERT_Pair *peerCert = NULL; ret = SAL_CERT_ParseCertChain(ctx, certs->cert, &peerCert); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15723, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "parse certificate list fail when process peer certificate.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_CERTIFICATE); return ret; } #ifdef HITLS_TLS_CONFIG_KEY_USAGE if (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11 && ctx->config.tlsConfig.needCheckKeyUsage == true && !CheckCertKeyUsage(ctx, peerCert)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17043, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckCertKeyUsage fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_CERTIFICATE); SAL_CERT_PairFree(ctx->config.tlsConfig.certMgrCtx, peerCert); return HITLS_CERT_ERR_KEYUSAGE; } #endif /* HITLS_TLS_CONFIG_KEY_USAGE */ if (ctx->isClient) { ret = ClientCheckCert(ctx, peerCert); } else { ret = ServerCheckCert(ctx, peerCert); } if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_CERTIFICATE); SAL_CERT_PairFree(ctx->config.tlsConfig.certMgrCtx, peerCert); return ret; } ctx->hsCtx->peerCert = peerCert; return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t VerifyCertChain(TLS_Ctx *ctx) { int32_t ret = SAL_CERT_VerifyCertChain(ctx, ctx->hsCtx->peerCert, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16228, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "process peer certificate fail, ret = 0x%x.", (uint32_t)ret, 0, 0, 0); return ret; } #ifdef HITLS_TLS_PROTO_TLCP11 if (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11) { return ret; } if (ctx->isClient) { ret = SAL_CERT_VerifyCertChain(ctx, ctx->hsCtx->peerCert, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16229, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "process client enc certificate fail, ret = 0x%x.", (uint32_t)ret, 0, 0, 0); } return ret; } /* Processing logic on the service side of TLCP, which is verified only when used. */ if (ctx->negotiatedInfo.cipherSuiteInfo.kxAlg == HITLS_KEY_EXCH_ECDHE) { ret = SAL_CERT_VerifyCertChain(ctx, ctx->hsCtx->peerCert, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16230, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "process server enc certificate fail, ret = 0x%x.", (uint32_t)ret, 0, 0, 0); } return ret; } #endif return ret; } /** * @brief Process the certificate. * * @param ctx [IN/OUT] TLS context * @param msg [IN] Packet structure * * @retval HITLS_SUCCESS succeeded. * @retval For other error codes, see hitls_error.h. */ int32_t RecvCertificateProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret; const CertificateMsg *certs = &msg->body.certificate; /** * RFC 5426 7.4.6:If no suitable certificate is available, * the client MUST send a certificate message containing no certificates. */ if (certs->certCount == 0) { /** Only the server allows the peer certificate to be empty */ if ((ctx->isClient == false) && (ctx->config.tlsConfig.isSupportClientVerify && ctx->config.tlsConfig.isSupportNoClientCert)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17105, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server recv empty cert", 0, 0, 0, 0); return HS_ChangeState(ctx, TRY_RECV_CLIENT_KEY_EXCHANGE); } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15724, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "peer certificate is needed!", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ctx->isClient ? ALERT_DECODE_ERROR : ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE; } /** Process the obtained peer certificate */ ret = ProcessPeerCertificate(ctx, certs); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15725, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "process peer certificate fail, ret = 0x%x.", ret, 0, 0, 0); return ret; } /** Verify the peer certificate */ ret = VerifyCertChain(ctx); /* After the VerifyNone function is enabled, the client can continue the handshake process if the server certificate * fails to be verified */ if (ret != HITLS_SUCCESS) { if (!ctx->config.tlsConfig.isSupportVerifyNone) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, GetAlertfromX509Err(ctx->peerInfo.verifyResult)); return ret; } } /** Update the state machine */ if (ctx->isClient) { if (IsNeedServerKeyExchange(ctx) == true) { return HS_ChangeState(ctx, TRY_RECV_SERVER_KEY_EXCHANGE); } return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE_REQUEST); } return HS_ChangeState(ctx, TRY_RECV_CLIENT_KEY_EXCHANGE); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t CertificateReqCtxCheck(TLS_Ctx *ctx, const CertificateMsg *certs) { #ifdef HITLS_TLS_FEATURE_PHA /* In the handshake phase, certificate_request_context must be empty. */ if (ctx->phaState != PHA_REQUESTED && certs->certificateReqCtxSize != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15726, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server receive a non-zero certificateReqCtx.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX; } /* pha phase, which must be non-empty and equal */ if (ctx->certificateReqCtxSize != 0 && (ctx->certificateReqCtxSize != certs->certificateReqCtxSize || memcmp(ctx->certificateReqCtx, certs->certificateReqCtx, certs->certificateReqCtxSize) != 0)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17044, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certificateReqCtx is not equal", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX; } #else if (certs->certificateReqCtxSize != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15732, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server receive a non-zero certificateReqCtx.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX; } #endif /* HITLS_TLS_FEATURE_PHA */ return HITLS_SUCCESS; } int32_t Tls13RecvCertificateProcess(TLS_Ctx *ctx, const HS_Msg *msg) { const CertificateMsg *certs = &msg->body.certificate; if (ctx->isClient == false) { ctx->plainAlertForbid = true; } int32_t ret = HS_CheckReceivedExtension( ctx, CERTIFICATE, certs->extensionTypeMask, HS_EX_TYPE_TLS1_3_ALLOWED_OF_CERTIFICATE); if (ret != HITLS_SUCCESS) { return ret; } ret = CertificateReqCtxCheck(ctx, certs); if (ret != HITLS_SUCCESS) { return ret; } /** * RFC 5426 7.4.6:If no suitable certificate is available, * the client MUST send a certificate message containing no certificates. */ if (certs->certCount == 0) { if (ctx->isClient) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); return RETURN_ALERT_PROCESS(ctx, HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE, BINLOG_ID16126, "peer certificate is needed!", ALERT_DECODE_ERROR); } /** Only the server allows the peer certificate to be empty */ if ((ctx->config.tlsConfig.isSupportClientVerify && ctx->config.tlsConfig.isSupportNoClientCert)) { ret = VERIFY_Tls13CalcVerifyData(ctx, true); if (ret != HITLS_SUCCESS) { return RETURN_ALERT_PROCESS(ctx, ret, BINLOG_ID15729, "server calculate client finished data error.", ALERT_INTERNAL_ERROR); } return HS_ChangeState(ctx, TRY_RECV_FINISH); } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); return RETURN_ALERT_PROCESS(ctx, HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE, BINLOG_ID15727, "peer certificate is needed!", ALERT_CERTIFICATE_REQUIRED); } /** Process the obtained peer certificate */ ret = ProcessPeerCertificate(ctx, certs); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15728, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "process peer certificate fail, ret = 0x%x.", ret, 0, 0, 0); return ret; } /** Verify the peer certificate */ ret = SAL_CERT_VerifyCertChain(ctx, ctx->hsCtx->peerCert, false); if (ret != HITLS_SUCCESS) { if (!ctx->config.tlsConfig.isSupportVerifyNone) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17045, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VerifyCertChain fail, ret = 0x%x.", (uint32_t)ret, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, GetAlertfromX509Err(ctx->peerInfo.verifyResult)); return ret; } } return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE_VERIFY); } #endif /* HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/recv/src/recv_certificate.c
C
unknown
21,529
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #include "tls.h" #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls.h" #include "hitls_error.h" #include "hitls_sni.h" #include "hitls_alpn.h" #include "hitls_security.h" #include "bsl_uio.h" #include "alert.h" #include "session_mgr.h" #include "recv_process.h" #include "config_check.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "sni.h" #include "hs_ctx.h" #include "hs.h" #include "hs_common.h" #include "hs_extensions.h" #include "hs_verify.h" #include "cert_mgr_ctx.h" #include "record.h" #include "hs_cookie.h" #ifdef HITLS_TLS_PROTO_TLS13 #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_FEATURE_PSK) #define HS_MAX_BINDER_SIZE 64 #endif #endif #ifdef HITLS_TLS_SUITE_KX_ECDHE /** * @brief Check the extension of the client hello point format. * * @param clientHello [IN] client hello packet * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT Unsupported point format */ static int32_t ServerCheckPointFormats(const ClientHelloMsg *clientHello) { /* Point format extension not received */ if (!clientHello->extension.flag.havePointFormats) { return HITLS_SUCCESS; } /* Traverse the list of point formats */ for (uint32_t i = 0u; i < clientHello->extension.content.pointFormatsSize; i++) { /* The point format list contains uncompressed (0) */ if (clientHello->extension.content.pointFormats[i] == 0u) { return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15210, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "the point format extension in client hello is unsupported.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT; } static uint16_t FindSupportedCurves(const TLS_Ctx *ctx, const uint16_t *perferenceGroups, uint32_t index) { /* Support group security check */ #ifdef HITLS_TLS_FEATURE_SECURITY int32_t id = (int32_t)perferenceGroups[index]; int32_t ret = SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_CURVE_SHARED, 0, id, NULL); if (ret != SECURITY_SUCCESS || !GroupConformToVersion(ctx, ctx->negotiatedInfo.version, perferenceGroups[index])) { #else if (!GroupConformToVersion(ctx, ctx->negotiatedInfo.version, perferenceGroups[index])) { #endif /* HITLS_TLS_FEATURE_SECURITY */ return 0; } return perferenceGroups[index]; } /** * @brief Select elliptic curve * * @param ctx [IN] TLS context * @param clientHello [IN] Client Hello packet * * @return Return curveID. If the value is 0, the supported curve is not found. */ static uint16_t ServerSelectCurveId(const TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { uint32_t perferenceGroupsSize = 0; uint32_t normalGroupsSize = 0; uint16_t *perferenceGroups = NULL; uint16_t *normalGroups = NULL; if (ctx->config.tlsConfig.isSupportServerPreference) { perferenceGroupsSize = ctx->config.tlsConfig.groupsSize; normalGroupsSize = clientHello->extension.content.supportedGroupsSize; perferenceGroups = ctx->config.tlsConfig.groups; normalGroups = clientHello->extension.content.supportedGroups; } else { perferenceGroupsSize = clientHello->extension.content.supportedGroupsSize; normalGroupsSize = ctx->config.tlsConfig.groupsSize; perferenceGroups = clientHello->extension.content.supportedGroups; normalGroups = ctx->config.tlsConfig.groups; } /* Find supported curves */ for (uint32_t i = 0u; i < perferenceGroupsSize; i++) { for (uint32_t j = 0u; j < normalGroupsSize; j++) { if (perferenceGroups[i] != normalGroups[j]) { continue; } uint16_t curve = FindSupportedCurves(ctx, perferenceGroups, i); if (curve == 0) { continue; } return curve; } } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_NAMED_CURVE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15211, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "the curve id in client hello is unsupported.", 0, 0, 0, 0); return 0; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ /** * @brief Select a proper certificate based on the TLS cipher suite. * * @param ctx [IN] TLS context * @param clientHello [IN] Client Hello packet * @param cipherInfo [IN] TLS cipher suite * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMALLOC_FAIL Memory application failed. */ static int32_t HsServerSelectCert(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, const CipherSuiteInfo *cipherInfo) { uint16_t signHashAlgo = cipherInfo->signScheme; CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CFG_GetCertTypeByCipherSuite(cipherInfo->cipherSuite); /* For TLCP1.1, ignore the signature extension of client hello */ if (clientHello->extension.content.signatureAlgorithms != NULL && (ctx->negotiatedInfo.version != HITLS_VERSION_TLCP_DTLCP11)) { expectCertInfo.signSchemeList = clientHello->extension.content.signatureAlgorithms; expectCertInfo.signSchemeNum = clientHello->extension.content.signatureAlgorithmsSize; } else { expectCertInfo.signSchemeList = &signHashAlgo; expectCertInfo.signSchemeNum = 1u; } /* The ECDSA certificate must match the supported_groups and ec_point_format extensions */ expectCertInfo.ellipticCurveList = clientHello->extension.content.supportedGroups; expectCertInfo.ellipticCurveNum = clientHello->extension.content.supportedGroupsSize; /* Only the uncompressed format is supported */ uint8_t pointFormat = HITLS_POINT_FORMAT_UNCOMPRESSED; expectCertInfo.ecPointFormatList = &pointFormat; expectCertInfo.ecPointFormatNum = 1u; return SAL_CERT_SelectCertByInfo(ctx, &expectCertInfo); } #ifdef HITLS_TLS_SUITE_KX_ECDHE #ifdef HITLS_TLS_PROTO_TLCP11 static bool CheckLocalContainCurveType(const uint16_t *groups, uint32_t groupsSize, uint16_t exp) { for (uint32_t i = 0; i < groupsSize; ++i) { if (groups[i] == exp) { return true; } } return false; } #endif /** * @brief Process the ECDHE cipher suite. * * @param ctx [IN] TLS context * @param clientHello [IN] Client Hello packet * @param cipherSuiteInfo [OUT] Cipher suite information * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE Unsupported cipher suites */ static int32_t ProcessEcdheCipherSuite(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* If the curve id is not set, ECDHE cannot be used. */ if ((ctx->config.tlsConfig.groupsSize == 0u) || (ctx->config.tlsConfig.groups == NULL)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15212, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "can not used ecdhe whitout curve id.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE; } #ifdef HITLS_TLS_PROTO_TLCP11 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { if (CheckLocalContainCurveType(ctx->config.tlsConfig.groups, ctx->config.tlsConfig.groupsSize, HITLS_EC_GROUP_SM2) != true) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16231, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "TLCP need sm2 curve.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE; } ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type = HITLS_EC_CURVE_TYPE_NAMED_CURVE; ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.param.namedcurve = HITLS_EC_GROUP_SM2; return HITLS_SUCCESS; /* TLCP negotiation does not focus on extended information. */ } #endif /* Check the Point format extension of the clientHello. This extension is not included in the TLCP */ int32_t ret = ServerCheckPointFormats(clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15213, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server check client hello point formats fail.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE; } uint16_t selectedEcCurveId = #ifdef HITLS_TLS_PROTO_TLS13 ctx->hsCtx->haveHrr ? ctx->negotiatedInfo.negotiatedGroup : #endif ServerSelectCurveId(ctx, clientHello); if (selectedEcCurveId == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15214, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server select curve id fail.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE; } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { ctx->hsCtx->kxCtx->keyExchParam.share.group = selectedEcCurveId; } else #endif /* HITLS_TLS_PROTO_TLS13 */ { ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.type = HITLS_EC_CURVE_TYPE_NAMED_CURVE; ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams.param.namedcurve = selectedEcCurveId; } ctx->negotiatedInfo.negotiatedGroup = selectedEcCurveId; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_ECDHE */ /** * @brief Check whether the server supports the cipher suite. * * @param ctx [IN] TLS context * @param clientHello [IN] client hello packet * @param cipher [IN] cipher suite ID * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMCPY_FAIL Memory Copy Failure * @retval HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE Unsupported cipher suites */ static int32_t ServerNegotiateCipher(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t cipher) { CipherSuiteInfo cipherSuiteInfo = {0}; int32_t ret = 0; ret = CFG_GetCipherSuiteInfo(cipher, &cipherSuiteInfo); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15215, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "get cipher suite info fail when processing client hello.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE; } /* If the key exchange algorithm is not PSK, DHE_PSK, or ECDHE_PSK, select a certificate. */ if (IsNeedCertPrepare(&cipherSuiteInfo) == true) { if (HsServerSelectCert(ctx, clientHello, &cipherSuiteInfo) != HITLS_SUCCESS) { /* No proper certificate */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15216, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "have no suitable cert.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE; } } switch (cipherSuiteInfo.kxAlg) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: /* the ECDHE of TLCP is also in this branch */ case HITLS_KEY_EXCH_ECDHE_PSK: /* The ECC cipher suite needs to process the supported_groups and ec_point_formats extensions */ ret = ProcessEcdheCipherSuite(ctx, clientHello); break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: case HITLS_KEY_EXCH_RSA: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: #endif case HITLS_KEY_EXCH_PSK: case HITLS_KEY_EXCH_RSA_PSK: ret = HITLS_SUCCESS; break; default: ret = HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE; } if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15217, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server process ecdhe cipher suite fail. kxAlg is %d", cipherSuiteInfo.kxAlg, 0, 0, 0); return ret; } ctx->hsCtx->kxCtx->keyExchAlgo = cipherSuiteInfo.kxAlg; (void)memcpy_s(&ctx->negotiatedInfo.cipherSuiteInfo, sizeof(CipherSuiteInfo), &cipherSuiteInfo, sizeof(CipherSuiteInfo)); return ret; } #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13ServerNegotiateCipher(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t cipher) { (void)clientHello; int32_t ret = 0; CipherSuiteInfo cipherSuiteInfo = {0}; ret = CFG_GetCipherSuiteInfo(cipher, &cipherSuiteInfo); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15218, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "get cipher suite info fail when processing client hello.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_CIPHER_SUITE; } (void)memcpy_s(&ctx->negotiatedInfo.cipherSuiteInfo, sizeof(CipherSuiteInfo), &cipherSuiteInfo, sizeof(CipherSuiteInfo)); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ static int32_t CheckCipherSuite(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t cipherSuite) { if (!IsCipherSuiteAllowed(ctx, cipherSuite)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17046, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "No proper cipher suite", 0, 0, 0, 0); return HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE; } int32_t ret = 0; #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { ret = Tls13ServerNegotiateCipher(ctx, clientHello, cipherSuite); } else #endif /* HITLS_TLS_PROTO_TLS13 */ { ret = ServerNegotiateCipher(ctx, clientHello, cipherSuite); } if (ret != HITLS_SUCCESS) { return ret; } /* Check the security level of ciphersuites */ CipherSuiteInfo *cipherSuiteInfo = &ctx->negotiatedInfo.cipherSuiteInfo; #ifdef HITLS_TLS_FEATURE_SECURITY ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_CIPHER_SHARED, 0, 0, (void *)cipherSuiteInfo); if (ret != SECURITY_SUCCESS) { ctx->hsCtx->kxCtx->keyExchAlgo = HITLS_KEY_EXCH_NULL; (void)memset_s(&ctx->hsCtx->kxCtx->keyExchParam, sizeof(ctx->hsCtx->kxCtx->keyExchParam), 0, sizeof(ctx->hsCtx->kxCtx->keyExchParam)); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17047, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SslCheck fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSECURE_CIPHER_SUITE); return HITLS_MSG_HANDLE_UNSECURE_CIPHER_SUITE; } #endif /* HITLS_TLS_FEATURE_SECURITY */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15221, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "chosen ciphersuite 0x%04x", cipherSuiteInfo->cipherSuite, 0, 0, 0); BSL_LOG_BINLOG_VARLEN(BINLOG_ID15894, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "chosen ciphersuite: %s", cipherSuiteInfo->name); return HITLS_SUCCESS; } // Select the cipher suite. int32_t ServerSelectCipherSuite(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* Obtain server information */ uint16_t *cfgCipherSuites = ctx->config.tlsConfig.cipherSuites; uint32_t cfgCipherSuitesSize = ctx->config.tlsConfig.cipherSuitesSize; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { cfgCipherSuites = ctx->config.tlsConfig.tls13CipherSuites; cfgCipherSuitesSize = ctx->config.tlsConfig.tls13cipherSuitesSize; } const uint16_t *preferenceCipherSuites = clientHello->cipherSuites; uint16_t preferenceCipherSuitesSize = clientHello->cipherSuitesSize; const uint16_t *normalCipherSuites = cfgCipherSuites; uint16_t normalCipherSuitesSize = (uint16_t)cfgCipherSuitesSize; if (ctx->config.tlsConfig.isSupportServerPreference) { preferenceCipherSuites = cfgCipherSuites; preferenceCipherSuitesSize = (uint16_t)cfgCipherSuitesSize; normalCipherSuites = clientHello->cipherSuites; normalCipherSuitesSize = clientHello->cipherSuitesSize; } /* Select the supported cipher suite. If the cipher suite is found, return success */ for (uint16_t i = 0u; i < preferenceCipherSuitesSize; i++) { for (uint32_t j = 0u; j < normalCipherSuitesSize; j++) { if (normalCipherSuites[j] != preferenceCipherSuites[i]) { continue; } if (CheckCipherSuite(ctx, clientHello, normalCipherSuites[j]) != HITLS_SUCCESS) { break; } return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15222, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "can not find a appropriate cipher suite.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_CIPHER_SUITE_ERR; } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static uint32_t MapLegacyVersionToBits(TLS_Ctx *ctx, uint16_t version) { uint32_t ret = 0; uint16_t versions[] = {HITLS_VERSION_DTLS12, HITLS_VERSION_TLS12, HITLS_VERSION_TLCP_DTLCP11}; bool isGreater = !IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) || IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask); for (uint32_t i = 0; i < sizeof(versions) / sizeof(versions[0]); i++) { if (isGreater? version >= versions[i] : version <= versions[i]) { ret |= MapVersion2VersionBit(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), versions[i]); } } if (IS_SUPPORT_TLS(ret) && IS_SUPPORT_TLCP(ret)) { ret &= ~TLCP_VERSION_BITS; } return ret; } /** * @brief Select the negotiation version based on the client Hello packet. * * @param ctx [IN] TLS context * @param clientHello [IN] client Hello packet * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MSG_HANDLE_UNSUPPORT_VERSION Unsupported version number */ static int32_t ServerSelectNegoVersion(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { uint16_t legacyVersion = clientHello->version; uint32_t legacyVersionBits = MapLegacyVersionToBits(ctx, legacyVersion); uint32_t intersection = ctx->config.tlsConfig.version & legacyVersionBits; if (intersection == 0) { if (TLS_IS_FIRST_HANDSHAKE(ctx)) { ctx->negotiatedInfo.version = legacyVersion; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15220, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client want a unsupported protocol version 0x%02x.", legacyVersion, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } uint16_t versions[] = {HITLS_VERSION_DTLS12, HITLS_VERSION_TLS12, HITLS_VERSION_TLCP_DTLCP11, HITLS_VERSION_TLCP_DTLCP11}; uint32_t versionBits[] = {DTLS12_VERSION_BIT, TLS12_VERSION_BIT, TLCP11_VERSION_BIT, DTLCP11_VERSION_BIT}; for (uint32_t i = 0; i < sizeof(versionBits) / sizeof(versionBits[0]); i++) { if (intersection & versionBits[i]) { ctx->negotiatedInfo.version = versions[i]; break; } } #ifdef HITLS_TLS_FEATURE_SECURITY int32_t ret = 0; /* Version security check */ ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_VERSION, 0, ctx->negotiatedInfo.version, NULL); if (ret != SECURITY_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSECURE_VERSION); return RETURN_ALERT_PROCESS(ctx, HITLS_MSG_HANDLE_UNSECURE_VERSION, BINLOG_ID17048, "SslCheck fail", ALERT_INSUFFICIENT_SECURITY); } #endif /* HITLS_TLS_FEATURE_SECURITY */ return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_FEATURE_ALPN static int32_t ServerSelectAlpnProtocol(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { uint8_t *alpnSelected = NULL; uint8_t alpnSelectedLen = 0u; /* If the callback is empty, the server does not have the ALPN processing capability. In this case, return success */ if (ctx->globalConfig != NULL && ctx->globalConfig->alpnSelectCb != NULL) { int32_t alpnCbRet = ctx->globalConfig->alpnSelectCb(ctx, &alpnSelected, &alpnSelectedLen, clientHello->extension.content.alpnList, clientHello->extension.content.alpnListSize, ctx->globalConfig->alpnUserData); if (alpnCbRet == HITLS_ALPN_ERR_OK) { uint8_t *alpnSelectedTmp = (uint8_t *)BSL_SAL_Calloc(alpnSelectedLen + 1, sizeof(uint8_t)); if (alpnSelectedTmp == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15227, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server malloc alpn buffer failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } if (memcpy_s(alpnSelectedTmp, alpnSelectedLen + 1, alpnSelected, alpnSelectedLen) != EOK) { BSL_SAL_FREE(alpnSelectedTmp); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16031, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server copy selected alpn failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMCPY_FAIL; } BSL_SAL_FREE(ctx->negotiatedInfo.alpnSelected); ctx->negotiatedInfo.alpnSelected = alpnSelectedTmp; ctx->negotiatedInfo.alpnSelectedSize = alpnSelectedLen; BSL_LOG_BINLOG_VARLEN(BINLOG_ID15228, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "select ALPN protocol: %s.", ctx->negotiatedInfo.alpnSelected); /* Based on RFC7301, if the server cannot match the application layer protocol in the client alpn list, it * sends a fatal alert to the peer end. * If the returned value is not HITLS_ALPN_ERR_NOACK, the system sends a fatal alert message to the peer */ } else if (alpnCbRet != HITLS_ALPN_ERR_NOACK) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ALPN_PROTOCOL_NO_MATCH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15229, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server invoke alpn select cb error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_NO_APPLICATION_PROTOCOL); return HITLS_MSG_HANDLE_ALPN_PROTOCOL_NO_MATCH; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_FEATURE_SNI static int32_t ServerDealServerName(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { int32_t ret = 0; int alert = ALERT_UNRECOGNIZED_NAME; uint32_t serverNameSize = clientHello->extension.content.serverNameSize; if (clientHello->extension.flag.haveServerName == false) { return HITLS_SUCCESS; } BSL_SAL_FREE(ctx->hsCtx->serverName); ctx->hsCtx->serverName = (uint8_t *)BSL_SAL_Dump(clientHello->extension.content.serverName, serverNameSize * sizeof(uint8_t)); if (ctx->hsCtx->serverName == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15230, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server_name malloc fail when parse extensions msg.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } ctx->hsCtx->serverNameSize = serverNameSize; /* The product does not have the registered server_name callback processing function */ if (ctx->globalConfig == NULL || ctx->globalConfig->sniDealCb == NULL) { /* Rejected, but continued handshake */ ctx->negotiatedInfo.isSniStateOK = false; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15231, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server did not set sni callback, but continue handshake", 0, 0, 0, 0); return HITLS_SUCCESS; } /* Execute the product callback function */ ret = ctx->globalConfig->sniDealCb(ctx, &alert, ctx->globalConfig->sniArg); switch (ret) { case HITLS_ACCEPT_SNI_ERR_OK: ctx->negotiatedInfo.isSniStateOK = true; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15232, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server accept server_name from client hello msg ", 0, 0, 0, 0); break; case HITLS_ACCEPT_SNI_ERR_NOACK: ctx->negotiatedInfo.isSniStateOK = false; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15233, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "server did not accept server_name from client hello msg, but continue handshake", 0, 0, 0, 0); break; case HITLS_ACCEPT_SNI_ERR_ALERT_FATAL: default: BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15234, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server did not accept server_name from client hello msg, stop handshake", 0, 0, 0, 0); ctx->negotiatedInfo.isSniStateOK = false; ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNRECOGNIZED_NAME); return HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SNI */ static int32_t ProcessClientHelloExt(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool isNeedSendHrr) { (void)ctx; (void)clientHello; (void)isNeedSendHrr; int32_t ret = HITLS_SUCCESS; ret = HS_CheckReceivedExtension( ctx, CLIENT_HELLO, clientHello->extensionTypeMask, HS_EX_TYPE_TLS_ALLOWED_OF_CLIENT_HELLO); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_ALPN if (clientHello->extension.flag.haveAlpn && !isNeedSendHrr && ctx->state == CM_STATE_HANDSHAKING) { ret = ServerSelectAlpnProtocol(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17049, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ServerSelectAlpnProtocol fail", 0, 0, 0, 0); /* Logs have been recorded internally */ return ret; } } #endif /* HITLS_TLS_FEATURE_ALPN */ return ret; } #ifdef HITLS_TLS_FEATURE_SESSION /* Validate the session ID ctx. */ bool ServerCmpSessionIdCtx(TLS_Ctx *ctx, HITLS_Session *sess) { #ifdef HITLS_TLS_FEATURE_SESSION_ID uint8_t sessionIdCtx[HITLS_SESSION_ID_CTX_MAX_SIZE]; uint32_t sessionIdCtxSize = HITLS_SESSION_ID_CTX_MAX_SIZE; if (HITLS_SESS_GetSessionIdCtx(sess, sessionIdCtx, &sessionIdCtxSize) != HITLS_SUCCESS) { return false; } /* The session ID ctx length is not equal to configured value. */ if (sessionIdCtxSize != ctx->config.tlsConfig.sessionIdCtxSize) { return false; } /* The session ID ctx is not equal to configured value. */ if (sessionIdCtxSize != 0 && memcmp(sessionIdCtx, ctx->config.tlsConfig.sessionIdCtx, sessionIdCtxSize) != 0) { return false; } #endif /* HITLS_TLS_FEATURE_SESSION_ID */ (void)ctx; (void)sess; return true; } #endif /* HITLS_TLS_FEATURE_SESSION */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #ifdef HITLS_TLS_FEATURE_RENEGOTIATION static void CheckRenegotiate(TLS_Ctx *ctx) { /* For the server, sending a Hello Request message is not considered as renegotiation. The server enters the * renegotiation state only after receiving a Hello message from the client. A non-zero version number * indicates that a handshake has been performed, in which case, the client hello process enters the * renegotiation state again. */ if (ctx->negotiatedInfo.version != 0u) { ctx->negotiatedInfo.isRenegotiation = true; // enters the renegotiation state. } return; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ #ifdef HITLS_TLS_FEATURE_SESSION #ifdef HITLS_TLS_FEATURE_ALPN static int32_t DealResumeAlpnEx(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { if (clientHello->extension.flag.haveAlpn && ctx->state == CM_STATE_HANDSHAKING) { return ServerSelectAlpnProtocol(ctx, clientHello); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_FEATURE_SNI static int32_t DealResumeServerName(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint32_t serverNameSize, uint8_t *serverName) { /* Continue processing only when the TLS protocol version <=TLS1.2 */ if (ctx->negotiatedInfo.version >= HITLS_VERSION_TLS13 && ctx->negotiatedInfo.version != HITLS_VERSION_DTLS12) { return HITLS_SUCCESS; } if (ctx->globalConfig != NULL && ctx->globalConfig->sniDealCb == NULL && serverNameSize == 0) { ctx->negotiatedInfo.isSniStateOK = false; return HITLS_SUCCESS; } if (serverName != NULL && serverNameSize != 0 && clientHello->extension.flag.haveServerName == false) { BSL_LOG_BINLOG_VARLEN(BINLOG_ID16119, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "during session resumption, session server name is [%s]", (char *)serverName); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16120, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "There is no server name in client hello msg.", 0, 0, 0, 0); ctx->negotiatedInfo.isSniStateOK = false; return HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME; } /* Compare the extended value of client hello server_name and the value of server_name in the session during session * resumption */ if (clientHello->extension.content.serverNameSize != serverNameSize || SNI_StrcaseCmp((char *)clientHello->extension.content.serverName, (char *)serverName) != 0) { BSL_LOG_BINLOG_VARLEN(BINLOG_ID15235, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "during session resume ,session servername is [%s]", (char *)serverName); BSL_LOG_BINLOG_VARLEN(BINLOG_ID15254, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server did not accept server_name [%s] from client hello msg", (char *)clientHello->extension.content.serverName); ctx->negotiatedInfo.isSniStateOK = false; return HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15236, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "during session resume, server accept server_name [%s] from client hello msg.", (char *)serverName, 0, 0, 0); return HITLS_SUCCESS; } static int32_t ServerCheckResumeSni(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, HITLS_Session **sess) { if (*sess == NULL || ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLCP_DTLCP11) { return HITLS_SUCCESS; } int32_t ret = HITLS_SUCCESS; uint8_t *serverName = NULL; uint32_t serverNameSize = 0; SESS_GetHostName(*sess, &serverNameSize, &serverName); /* During session recovery, the server processes the server_name extension in the ClientHello */ ret = DealResumeServerName(ctx, clientHello, serverNameSize, serverName); if (ret != HITLS_SUCCESS) { HITLS_SESS_Free(*sess); *sess = NULL; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SNI */ int32_t ServerCheckResumeCipherSuite(const ClientHelloMsg *clientHello, uint16_t cipherSuite) { for (uint16_t i = 0u; i < clientHello->cipherSuitesSize; i++) { if (cipherSuite == clientHello->cipherSuites[i]) { return HITLS_SUCCESS; } } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15237, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "Client's cipher suites do not match resume cipher suite.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE; } static int32_t ServerCheckResumeParam(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { int32_t ret = HITLS_SUCCESS; uint16_t version = 0; uint16_t cipherSuite = 0; HITLS_Session *sess = ctx->session; HITLS_SESS_GetProtocolVersion(sess, &version); HITLS_SESS_GetCipherSuite(sess, &cipherSuite); if (ServerCmpSessionIdCtx(ctx, sess) != true) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15886, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Resuming Sessions: session id ctx is inconsistent.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_SESSION_ID_CTX_ILLEGAL; } if (ctx->negotiatedInfo.version != version) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15887, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Resuming Sessions: version is inconsistent.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_MSG_HANDLE_ILLEGAL_VERSION; } ret = ServerCheckResumeCipherSuite(clientHello, cipherSuite); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return ret; } ret = CFG_GetCipherSuiteInfo(cipherSuite, &ctx->negotiatedInfo.cipherSuiteInfo); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17050, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "GetCipherSuiteInfo fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #ifdef HITLS_TLS_FEATURE_ALPN /* During session resumption, the server processes the ALPN extension in the ClientHello message */ return DealResumeAlpnEx(ctx, clientHello); #else return HITLS_SUCCESS; #endif /* HITLS_TLS_FEATURE_ALPN */ } /* rfc7627 5.3 If a server receives a ClientHello for an abbreviated handshake offering to resume a known previous session, it behaves as follows: -------------------------------------------------------------------------------------------------------- | original session | abbreviated handshake | Server behavior | | :-------------: | :--------------------: | :---------------------------------------------------------:| | true | true | SH with ems, agree resume | | true | false | abort handshake | | false | true | disagre resume, full handshake | | false | false | depend cnf: abort handshake(true) / agree resume (false) | */ static int32_t ResumeCheckExtendedMasterScret(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, HITLS_Session **sess) { if (*sess == NULL || ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLCP_DTLCP11) { return HITLS_SUCCESS; } (void)clientHello; uint8_t haveExtMasterSecret = false; HITLS_SESS_GetHaveExtMasterSecret(*sess, &haveExtMasterSecret); if (haveExtMasterSecret != 0) { if (!clientHello->extension.flag.haveExtendedMasterSecret) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17051, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ExtendedMasterSecret err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET; } ctx->negotiatedInfo.isExtendedMasterSecret = true; } else { if (clientHello->extension.flag.haveExtendedMasterSecret) { HITLS_SESS_Free(*sess); *sess = NULL; } else if (ctx->config.tlsConfig.isSupportExtendMasterSecret) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17052, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ExtendedMasterSecret err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET; } ctx->negotiatedInfo.isExtendedMasterSecret = clientHello->extension.flag.haveExtendedMasterSecret; } #ifdef HITLS_TLS_FEATURE_SNI return ServerCheckResumeSni(ctx, clientHello, sess); #else return HITLS_SUCCESS; #endif /* HITLS_TLS_FEATURE_SNI */ } #ifdef HITLS_TLS_FEATURE_SESSION_TICKET static int32_t ServerCheckResumeTicket(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { TLS_SessionMgr *sessMgr = ctx->config.tlsConfig.sessMgr; HITLS_Session *sess = NULL; uint8_t *ticketBuf = clientHello->extension.content.ticket; uint32_t ticketBufSize = clientHello->extension.content.ticketSize; bool isTicketExpect = false; int32_t ret = SESSMGR_DecryptSessionTicket(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), sessMgr, &sess, ticketBuf, ticketBufSize, &isTicketExpect); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16045, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESSMGR_DecryptSessionTicket return fail when process client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ctx->negotiatedInfo.isTicket = isTicketExpect; ret = ResumeCheckExtendedMasterScret(ctx, clientHello, &sess); if (ret != HITLS_SUCCESS) { HITLS_SESS_Free(sess); sess = NULL; return ret; } if (sess != NULL) { /* Check whether the session is valid */ if (SESS_CheckValidity(sess, (uint64_t)BSL_SAL_CurrentSysTimeGet()) == false) { /* If the session is invalid, a message is returned and the session is not resume. The complete connection * is established */ ctx->negotiatedInfo.isTicket = true; HITLS_SESS_Free(sess); return HITLS_SUCCESS; } HITLS_SESS_Free(ctx->session); ctx->session = sess; ctx->negotiatedInfo.isResume = true; /* If the session is resumed and the session ID of the clientHello is not empty, the session ID needs to be * filled in the serverHello and returned */ HITLS_SESS_SetSessionId(ctx->session, clientHello->sessionId, clientHello->sessionIdSize); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ /* Check whether the resume function is supported */ static int32_t ServerCheckResume(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { ctx->negotiatedInfo.isResume = false; ctx->negotiatedInfo.isTicket = false; /* If session resumption is not allowed in the renegotiation state, return */ if (ctx->negotiatedInfo.isRenegotiation && !ctx->config.tlsConfig.isResumptionOnRenego) { return HITLS_SUCCESS; } /* Obtain the session resumption information */ TLS_SessionMgr *sessMgr = ctx->config.tlsConfig.sessMgr; /* Create a null session handle */ HITLS_Session *sess = NULL; uint32_t ticketBufSize = clientHello->extension.content.ticketSize; bool supportTicket = IsTicketSupport(ctx); /* rfc5077 3.4 If a ticket is presented by the client, the server MUST NOT attempt to use the Session ID in the ClientHello for stateful session resumption. */ if (ticketBufSize == 0u) { if (supportTicket && clientHello->extension.flag.haveTicket) { ctx->negotiatedInfo.isTicket = true; } sess = HITLS_SESS_Dup(SESSMGR_Find(sessMgr, clientHello->sessionId, clientHello->sessionIdSize)); int32_t ret = ResumeCheckExtendedMasterScret(ctx, clientHello, &sess); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17053, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ResumeCheckExtendedMasterScret fail", 0, 0, 0, 0); HITLS_SESS_Free(sess); sess = NULL; return ret; } if (sess != NULL) { /* Update session handle information */ HITLS_SESS_Free(ctx->session); ctx->session = sess; // has ensured that it will not fail sess = NULL; ctx->negotiatedInfo.isResume = true; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SESSION_TICKET if (supportTicket) { return ServerCheckResumeTicket(ctx, clientHello); } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION */ static int32_t ServerCheckRenegoInfoDuringFirstHandshake(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* If the peer does not support security renegotiation, the system returns */ if (!clientHello->haveEmptyRenegoScsvCipher && !clientHello->extension.flag.haveSecRenego) { return HITLS_SUCCESS; } /* For the first handshake, if the security renegotiation information is not empty, a failure message is returned */ if (clientHello->extension.content.secRenegoInfoSize != 0) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15889, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "secRenegoInfoSize should be 0 in server initial handhsake.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } /* Setting the Support for Security Renegotiation */ ctx->negotiatedInfo.isSecureRenegotiation = true; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION static int32_t ServerCheckRenegoInfoDuringRenegotiation(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* If the renegotiation status contains the SCSV cipher suite, a failure message is returned */ if (clientHello->haveEmptyRenegoScsvCipher) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15890, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SCSV cipher should not be in server secure renegotiation.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } /* Verify the security renegotiation information */ if (clientHello->extension.content.secRenegoInfoSize != ctx->negotiatedInfo.clientVerifyDataSize) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15891, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "secRenegoInfoSize verify failed during server renegotiation.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } if (memcmp(clientHello->extension.content.secRenegoInfo, ctx->negotiatedInfo.clientVerifyData, ctx->negotiatedInfo.clientVerifyDataSize) != 0) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15892, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "secRenegoInfo verify failed during server renegotiation.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ static int32_t ServerCheckAndProcessRenegoInfo(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* Not in the renegotiation state */ if (!ctx->negotiatedInfo.isRenegotiation) { return ServerCheckRenegoInfoDuringFirstHandshake(ctx, clientHello); } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION /* in the renegotiation state */ return ServerCheckRenegoInfoDuringRenegotiation(ctx, clientHello); #else return HITLS_SUCCESS; #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ } #ifdef HITLS_TLS_FEATURE_ETM static int32_t ServerCheckEncryptThenMac(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { bool haveEncryptThenMac = clientHello->extension.flag.haveEncryptThenMac; /* Renegotiation cannot be downgraded from EncryptThenMac to MacThenEncrypt */ if (ctx->negotiatedInfo.isRenegotiation && ctx->negotiatedInfo.isEncryptThenMac && !haveEncryptThenMac) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ENCRYPT_THEN_MAC_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15919, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "regotiation should not change encrypt then mac to mac then encrypt.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_ENCRYPT_THEN_MAC_ERR; } /* If EncryptThenMac is not configured, a success message is returned. */ if (!ctx->config.tlsConfig.isEncryptThenMac) { return HITLS_SUCCESS; } /* TLS 1.3 does not need to negotiate this expansion. */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { return HITLS_SUCCESS; } /* Only the CBC cipher suite has the EncryptThenMac setting. */ if (haveEncryptThenMac && ctx->negotiatedInfo.cipherSuiteInfo.cipherType == HITLS_CBC_CIPHER) { ctx->negotiatedInfo.isEncryptThenMac = true; } else { ctx->negotiatedInfo.isEncryptThenMac = false; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ETM */ static int32_t ServerSelectCipherSuiteInfo(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { int32_t ret = ServerSelectCipherSuite(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15239, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server select cipher suite fail.", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_FEATURE_ETM /* Select the encryption mode (EncryptThenMac/MacThenEncrypt) */ ret = ServerCheckEncryptThenMac(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_ETM */ return HITLS_SUCCESS; } static int32_t ServerProcessClientHelloExt(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { int32_t ret = HITLS_SUCCESS; (void)ret; (void)clientHello; (void)ctx; /* Sets the extended master key flag */ if (ctx->negotiatedInfo.version > HITLS_VERSION_SSL30 && ctx->config.tlsConfig.isSupportExtendMasterSecret && !clientHello->extension.flag.haveExtendedMasterSecret) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16196, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "The peer does not support the extended master key.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET; } ctx->negotiatedInfo.isExtendedMasterSecret = clientHello->extension.flag.haveExtendedMasterSecret; return ProcessClientHelloExt(ctx, clientHello, false); } static int32_t ServerCheckVersionDowngrade(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { if (!clientHello->haveFallBackScsvCipher) { return HITLS_SUCCESS; } if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && !IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask)) { if (ctx->negotiatedInfo.version > ctx->config.tlsConfig.maxVersion) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15339, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dtls server supports a higher protocol version.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INAPPROPRIATE_FALLBACK); return HITLS_MSG_HANDLE_ERR_INAPPROPRIATE_FALLBACK; } return HITLS_SUCCESS; } if (ctx->negotiatedInfo.version < ctx->config.tlsConfig.maxVersion) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15335, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server supports a higher protocol version.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INAPPROPRIATE_FALLBACK); return HITLS_MSG_HANDLE_ERR_INAPPROPRIATE_FALLBACK; } return HITLS_SUCCESS; } // Check client Hello messages static int32_t ServerCheckAndProcessClientHello(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Negotiated version */ int32_t ret = ServerSelectNegoVersion(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15238, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server select negotiated version fail.", 0, 0, 0, 0); return ret; } ret = ServerCheckVersionDowngrade(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } /* Copy random numbers */ (void)memcpy_s(hsCtx->clientRandom, HS_RANDOM_SIZE, clientHello->randomValue, HS_RANDOM_SIZE); ret = ServerCheckAndProcessRenegoInfo(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_SESSION ret = ServerCheckResume(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } if (ctx->negotiatedInfo.isResume) { return ServerCheckResumeParam(ctx, clientHello); } #endif /* HITLS_TLS_FEATURE_SESSION */ #ifdef HITLS_TLS_FEATURE_SNI /* The message contains a server_name extension with the length greater than 0 */ ret = ServerDealServerName(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_SNI */ return ret; } static int32_t ServerPostProcessClientHello(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { int32_t ret; #ifdef HITLS_TLS_FEATURE_CERT_CB ret = ProcessCertCallback(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CERT_CB */ ret = ServerSelectCipherSuiteInfo(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } /* TLCP does not pay attention to the extension */ #ifdef HITLS_TLS_PROTO_TLCP11 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { return HITLS_SUCCESS; } #endif return ServerProcessClientHelloExt(ctx, clientHello); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB static int32_t ClientHelloCbCheck(TLS_Ctx *ctx) { int32_t ret; int32_t alert = ALERT_INTERNAL_ERROR; const TLS_Config *tlsConfig = ctx->globalConfig; if (tlsConfig != NULL && tlsConfig->clientHelloCb != NULL) { ret = tlsConfig->clientHelloCb(ctx, &alert, tlsConfig->clientHelloCbArg); if (ret == HITLS_CLIENT_HELLO_RETRY) { BSL_ERR_PUSH_ERROR(HITLS_CALLBACK_CLIENT_HELLO_RETRY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15239, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ClientHello callback error.", 0, 0, 0, 0); ctx->rwstate = HITLS_CLIENT_HELLO_CB; return HITLS_CALLBACK_CLIENT_HELLO_RETRY; } else if (ret != HITLS_CLIENT_HELLO_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_CALLBACK_CLIENT_HELLO_ERROR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15240, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "The result of ClientHello callback is %d, and the reason is %d.", ret, alert, 0, 0); if (alert >= ALERT_CLOSE_NOTIFY && alert <= ALERT_UNKNOWN) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, alert); } return HITLS_CALLBACK_CLIENT_HELLO_ERROR; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */ #ifdef HITLS_TLS_FEATURE_CERT_CB int32_t ProcessCertCallback(TLS_Ctx *ctx) { CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; if (mgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15229, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certMgrCtx is null when process client hello.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } HITLS_CertCb certCb = mgrCtx->certCb; void *certCbArg = mgrCtx->certCbArg; if (certCb != NULL) { /* Call the certificate callback function */ int32_t ret = certCb(ctx, certCbArg); if (ret == HITLS_CERT_CALLBACK_RETRY) { BSL_ERR_PUSH_ERROR(HITLS_CALLBACK_CERT_RETRY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15243, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certCb suspend when process client hello.", 0, 0, 0, 0); ctx->rwstate = HITLS_X509_LOOKUP; return HITLS_CALLBACK_CERT_RETRY; } else if (ret != HITLS_CERT_CALLBACK_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_CALLBACK_CERT_ERROR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15243, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certCb fail when process client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_CALLBACK_CERT_ERROR; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_CERT_CB */ #ifdef HITLS_TLS_PROTO_TLS_BASIC int32_t Tls12ServerRecvClientHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg, bool isNeedClientHelloCb) { int32_t ret = HITLS_SUCCESS; const ClientHelloMsg *clientHello = &msg->body.clientHello; #ifdef HITLS_TLS_FEATURE_RENEGOTIATION CheckRenegotiate(ctx); #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_A) { #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB /* Perform the ClientHello callback. The pause handshake status is not considered */ if (isNeedClientHelloCb) { ret = ClientHelloCbCheck(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #else (void)isNeedClientHelloCb; // Avoid unused parameter warning #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */ /* Process the client Hello message */ ret = ServerCheckAndProcessClientHello(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17055, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckAndProcessClientHello fail.", 0, 0, 0, 0); return ret; } if (!ctx->negotiatedInfo.isResume) { ctx->hsCtx->readSubState = TLS_PROCESS_STATE_B; } } if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_B) { ret = ServerPostProcessClientHello(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17056, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PostProcessClientHello fail.", 0, 0, 0, 0); return ret; } } if (ctx->state == CM_STATE_RENEGOTIATION && !ctx->userRenego) { ctx->negotiatedInfo.isRenegotiation = true; /* Start renegotiation */ ctx->negotiatedInfo.renegotiationNum++; } return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO); } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static int32_t PrepareDtlsCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { int32_t ret; uint8_t cookie[TLS_HS_MAX_COOKIE_SIZE] = {0}; uint32_t cookieSize = TLS_HS_MAX_COOKIE_SIZE; ret = HS_CalcCookie(ctx, clientHello, cookie, &cookieSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15241, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "calc cookie fail when process client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } BSL_SAL_FREE(ctx->negotiatedInfo.cookie); // Releasing the Old Cookie ctx->negotiatedInfo.cookie = (uint8_t *)BSL_SAL_Dump(cookie, cookieSize); if (ctx->negotiatedInfo.cookie == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15242, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc cookie fail when process client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } ctx->negotiatedInfo.cookieSize = (uint32_t)cookieSize; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ #ifdef HITLS_BSL_UIO_UDP static int32_t DtlsServerCheckAndProcessCookie(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isCookieValid) { int32_t ret; ret = HS_CheckCookie(ctx, clientHello, isCookieValid); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15243, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HS_CheckCookie fail when process client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } /* If the cookie fails to be verified, send a hello verify request */ if (!*isCookieValid) { /* During DTLS renegotiation, if the cookie verification fails, an alert message is sent. If the cookie is empty, the hello verify request is sent */ if ((clientHello->cookieLen != 0u) && (ctx->negotiatedInfo.isRenegotiation)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_VERIFY_COOKIE_ERR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15911, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client hello cookie verify fail during renegotiation.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_VERIFY_COOKIE_ERR; } ret = PrepareDtlsCookie(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } #endif /* HITLS_BSL_UIO_UDP */ // The server processes the DTLS client hello message. #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsServerRecvClientHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret; const ClientHelloMsg *clientHello = &msg->body.clientHello; #ifdef HITLS_TLS_FEATURE_RENEGOTIATION CheckRenegotiate(ctx); #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_A) { #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB /* Perform the ClientHello callback. The pause handshake status is not considered */ ret = ClientHelloCbCheck(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */ #ifdef HITLS_BSL_UIO_UDP if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { bool isCookieValid = false; ret = DtlsServerCheckAndProcessCookie(ctx, clientHello, &isCookieValid); if (ret == HITLS_SUCCESS && !isCookieValid) { return HS_ChangeState(ctx, TRY_SEND_HELLO_VERIFY_REQUEST); } else if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_BSL_UIO_UDP */ /* Process the client Hello message */ ret = ServerCheckAndProcessClientHello(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15244, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server process clientHello fail.", 0, 0, 0, 0); return ret; } if (!ctx->negotiatedInfo.isResume) { ctx->hsCtx->readSubState = TLS_PROCESS_STATE_B; } } if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_B) { ret = ServerPostProcessClientHello(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17056, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PostProcessClientHello fail.", 0, 0, 0, 0); return ret; } } if (ctx->state == CM_STATE_RENEGOTIATION && !ctx->userRenego) { ctx->negotiatedInfo.isRenegotiation = true; /* Start renegotiation */ ctx->negotiatedInfo.renegotiationNum++; } return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO); } #endif #ifdef HITLS_TLS_PROTO_TLS13 static uint32_t GetClientKeMode(const ExtensionContent *extension) { uint32_t clientKeMode = 0; for (uint32_t i = 0; i < extension->keModesSize; i++) { /* Ignore the received keMode of other types */ if (extension->keModes[i] == PSK_KE) { clientKeMode |= TLS13_KE_MODE_PSK_ONLY; } else if (extension->keModes[i] == PSK_DHE_KE) { clientKeMode |= TLS13_KE_MODE_PSK_WITH_DHE; } } return clientKeMode; } static bool CheckClientHelloKeyShareValid(const ClientHelloMsg *clientHello, uint16_t keyShareGroup) { for (uint32_t i = 0; i < clientHello->extension.content.supportedGroupsSize; i++) { if (keyShareGroup == clientHello->extension.content.supportedGroups[i]) { return true; } } return false; } static int32_t ServerCheckKeyShare(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* Prerequisite. If the PSK is not negotiated or the PSK requires dhe, a handshake failure message needs to be * reported if the keyshare does not exist */ if (clientHello->extension.flag.haveKeyShare == false || clientHello->extension.content.supportedGroupsSize == 0u || ProcessEcdheCipherSuite(ctx, clientHello) != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_HANDSHAKE_FAILURE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16137, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unable to negotiate a supported set of parameters.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_HANDSHAKE_FAILURE; } /* ProcessEcdheCipherSuite returns a success response. There must be a public group */ KeyShareParam *keyShare = &ctx->hsCtx->kxCtx->keyExchParam.share; uint16_t selectGroup = keyShare->group; KeyShare *cache = clientHello->extension.content.keyShare; /* rfc8446 4.2.8 Otherwise, when sending the new ClientHello, the client MUST replace the original "key_share" extension with one containing only a new KeyShareEntry for the group indicated in the selected_group field of the triggering HelloRetryRequest. */ if (ctx->hsCtx->haveHrr) { if (cache == NULL || cache->head.next != cache->head.prev || // parse must contain elements. LIST_ENTRY(cache->head.next, KeyShare, head)->group != selectGroup) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16164, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "hrr client hello key Share error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } } return HITLS_SUCCESS; } static int32_t Tls13ServerProcessKeyShare(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, bool *isNeedSendHrr) { /* Prerequisite. If the PSK is not negotiated or the PSK requires dhe, a handshake failure message needs to be * reported if the keyshare does not exist */ int32_t ret = ServerCheckKeyShare(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } /* ServerCheckKeyShare returns a success response. There must be a public group */ KeyShareParam *keyShare = &ctx->hsCtx->kxCtx->keyExchParam.share; uint16_t selectGroup = keyShare->group; ListHead *node = NULL; ListHead *tmpNode = NULL; KeyShare *cur = NULL; KeyShare *cache = clientHello->extension.content.keyShare; if (cache == NULL) { /* According to section 4.2.8 in RFC8446, if the client requests HelloRetryRequest, keyShare can be empty */ *isNeedSendHrr = true; return HITLS_SUCCESS; } LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(cache->head)) { cur = LIST_ENTRY(node, KeyShare, head); /* rfc8446 4.2.8 Clients MUST NOT offer any KeyShareEntry values for groups not listed in the client's "supported_groups" extension. Servers MAY check for violations of these rules and abort the handshake with an "illegal_parameter" alert if one is violated. */ if (!CheckClientHelloKeyShareValid(clientHello, cur->group)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16138, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "The group in the keyshare does not exist in the support group extension.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } if (cur->group != selectGroup) { continue; } *isNeedSendHrr = false; /* Obtain the peer public key */ ctx->hsCtx->kxCtx->pubKeyLen = cur->keyExchangeSize; if (SAL_CRYPT_GetCryptLength(ctx, HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN, keyShare->group) != ctx->hsCtx->kxCtx->pubKeyLen) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16189, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid keyShare length.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } BSL_SAL_FREE(ctx->hsCtx->kxCtx->peerPubkey); ctx->hsCtx->kxCtx->peerPubkey = BSL_SAL_Dump(cur->keyExchange, cur->keyExchangeSize); if (ctx->hsCtx->kxCtx->peerPubkey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15245, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc peerPubkey fail when process client key share.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ctx->negotiatedInfo.negotiatedGroup = selectGroup; return HITLS_SUCCESS; } /* If the server selects a group that does not exist in the keyshare, the server needs to send a hello retry request */ *isNeedSendHrr = true; return HITLS_SUCCESS; } #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_FEATURE_PSK) static int32_t GetPskFromSession(TLS_Ctx *ctx, HITLS_Session *pskSession, uint8_t *psk, uint32_t pskLen, uint32_t *usedLen) { /* The session is available and the PSK is obtained */ uint32_t tmpLen = pskLen; int32_t ret = HITLS_SESS_GetMasterKey(pskSession, psk, &tmpLen); if (ret != HITLS_SUCCESS) { /* An internal error occurs and cannot be continued. A failure message is returned and an alert message is sent */ ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } *usedLen = tmpLen; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_PSK static int32_t PskFindSession(TLS_Ctx *ctx, const uint8_t *id, uint32_t idLen, HITLS_Session **pskSession) { if (ctx->config.tlsConfig.pskFindSessionCb == NULL) { /* No callback is set */ return HITLS_SUCCESS; } int32_t ret = ctx->config.tlsConfig.pskFindSessionCb(ctx, id, idLen, pskSession); if (ret != HITLS_PSK_FIND_SESSION_CB_SUCCESS) { /* Internal error, cannot continue */ ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_PSK_FIND_SESSION_FAIL; } return HITLS_SUCCESS; } static int32_t GetPskByIdentity(TLS_Ctx *ctx, const uint8_t *id, uint32_t idLen, uint8_t *psk, uint32_t *pskLen) { if (ctx->config.tlsConfig.pskServerCb == NULL) { *pskLen = 0; return HITLS_SUCCESS; } uint8_t *strId = BSL_SAL_Calloc(1u, idLen + 1); if (strId == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17056, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(strId, idLen + 1, id, idLen); strId[idLen] = '\0'; uint32_t usedLen = ctx->config.tlsConfig.pskServerCb(ctx, strId, psk, *pskLen); BSL_SAL_FREE(strId); if (usedLen > HS_PSK_MAX_LEN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17057, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "usedLen err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN; } *pskLen = usedLen; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PSK */ static int32_t Tls13ServerSetPskInfo(TLS_Ctx *ctx, uint8_t *psk, uint32_t pskLen, uint16_t index) { PskInfo13 *pskInfo13 = &ctx->hsCtx->kxCtx->pskInfo13; BSL_SAL_FREE(pskInfo13->psk); pskInfo13->psk = BSL_SAL_Dump(psk, pskLen); if (pskInfo13->psk == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17058, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } pskInfo13->pskLen = pskLen; pskInfo13->selectIndex = index; return HITLS_SUCCESS; } static bool IsPSKValid(TLS_Ctx *ctx, HITLS_Session *pskSession) { uint16_t version, cipherSuite; HITLS_SESS_GetProtocolVersion(pskSession, &version); if (version != HITLS_VERSION_TLS13) { return false; } HITLS_SESS_GetCipherSuite(pskSession, &cipherSuite); CipherSuiteInfo cipherInfo = {0}; int32_t ret = CFG_GetCipherSuiteInfo(cipherSuite, &cipherInfo); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17059, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetCipherSuiteInfo fail", 0, 0, 0, 0); return false; } if (cipherInfo.hashAlg != ctx->negotiatedInfo.cipherSuiteInfo.hashAlg) { return false; } return true; } static int32_t TLS13ServerProcessTicket(TLS_Ctx *ctx, PreSharedKey *cur, uint8_t *psk, uint32_t *pskLen) { const uint8_t *ticket = cur->identity; uint32_t ticketLen = cur->identitySize; bool isTicketExcept = 0; HITLS_Session *pskSession = NULL; int32_t ret = SESSMGR_DecryptSessionTicket(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), ctx->config.tlsConfig.sessMgr, &pskSession, ticket, ticketLen, &isTicketExcept); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16048, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Decrypt Ticket fail when processing client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } /* Do not resume the session. TLS1.3 does not need to check isTicketExceptt */ if (pskSession == NULL) { *pskLen = 0; return HITLS_SUCCESS; } /* Check whether the session is valid */ if (!IsPSKValid(ctx, pskSession) || !SESS_CheckValidity(pskSession, (uint64_t)BSL_SAL_CurrentSysTimeGet())) { /* Do not resume the session */ *pskLen = 0; HITLS_SESS_Free(pskSession); return HITLS_SUCCESS; } if (ServerCmpSessionIdCtx(ctx, pskSession) != true) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16075, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TLS1.3 Resuming Session: session id ctx is inconsistent.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); HITLS_SESS_Free(pskSession); return HITLS_MSG_HANDLE_SESSION_ID_CTX_ILLEGAL; } ret = GetPskFromSession(ctx, pskSession, psk, *pskLen, pskLen); if (ret != HITLS_SUCCESS) { HITLS_SESS_Free(pskSession); return ret; } if (*pskLen == 0) { HITLS_SESS_Free(pskSession); return HITLS_SUCCESS; } HITLS_SESS_Free(ctx->session); ctx->session = pskSession; ctx->negotiatedInfo.isResume = true; return HITLS_SUCCESS; } static int32_t ServerFindPsk(TLS_Ctx *ctx, PreSharedKey *cur, uint8_t *psk, uint32_t *pskLen) { int32_t ret = HITLS_SUCCESS; ctx->negotiatedInfo.isResume = false; #ifdef HITLS_TLS_FEATURE_PSK const uint8_t *identity = cur->identity; uint32_t identitySize = cur->identitySize; uint32_t pskSize = *pskLen; HITLS_Session *pskSession = NULL; ret = PskFindSession(ctx, identity, identitySize, &pskSession); if (ret != HITLS_SUCCESS) { return ret; } /* TLS 1.3 processing */ if (pskSession != NULL) { /* In TLS1.3, pskSession is transferred by the user. Check the corresponding version and cipher suite */ if (IsPSKValid(ctx, pskSession) == false) { HITLS_SESS_Free(pskSession); /* Unsuitable sessions are released. */ *pskLen = 0; return HITLS_SUCCESS; } ret = GetPskFromSession(ctx, pskSession, psk, pskSize, pskLen); HITLS_SESS_Free(pskSession); /* After the session is used, the session is released. */ return ret; } /* * By default, the hash algorithm used by the pskSession cipher suite is SHA_256. * In this case, you only need to check whether the hash algorithm of the negotiated cipher suite is SHA_256. */ if (ctx->negotiatedInfo.cipherSuiteInfo.hashAlg == HITLS_HASH_SHA_256) { ret = GetPskByIdentity(ctx, identity, identitySize, psk, &pskSize); if (ret != HITLS_SUCCESS) { /* An internal error occurs and the process cannot be continued. An error code is returned */ return ret; } if (pskSize > 0u) { *pskLen = pskSize; return HITLS_SUCCESS; } } #endif /* HITLS_TLS_FEATURE_PSK */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET /* Try to decrypt the ticket for session resumption */ ret = TLS13ServerProcessTicket(ctx, cur, psk, pskLen); #else if (ret == HITLS_SUCCESS && *pskLen != 0) { *pskLen = 0; return HITLS_SUCCESS; } #endif return ret; } int32_t CompareBinder(TLS_Ctx *ctx, const PreSharedKey *pskNode, uint8_t *psk, uint32_t pskLen, uint32_t truncateHelloLen) { int32_t ret; uint8_t *recvBinder = pskNode->binder; uint32_t recvBinderLen = pskNode->binderSize; HITLS_HashAlgo hashAlg = ctx->negotiatedInfo.cipherSuiteInfo.hashAlg; bool isExternalPsk = !(ctx->negotiatedInfo.isResume); uint8_t computedBinder[HS_MAX_BINDER_SIZE] = {0}; uint32_t binderLen = HS_GetBinderLen(NULL, &hashAlg); if (binderLen == 0 || binderLen != recvBinderLen || binderLen > HS_MAX_BINDER_SIZE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17060, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "binderLen err", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } ret = VERIFY_CalcPskBinder(ctx, hashAlg, isExternalPsk, psk, pskLen, ctx->hsCtx->msgBuf, truncateHelloLen, computedBinder, binderLen); if (ret != HITLS_SUCCESS) { return ret; } ret = memcmp(computedBinder, recvBinder, binderLen); if (ret != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17061, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcmp fail, ret %d", ret, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } return ret; } /* Prior to accepting PSK key establishment, the server MUST validate the corresponding binder value (see Section 4.2.11.2 below). If this value is not present or does not validate, the server MUST abort the handshake. Servers SHOULD NOT attempt to validate multiple binders; rather, they SHOULD select a single PSK and validate solely the binder that corresponds to that PSK. */ static int32_t ServerSelectPskAndCheckBinder(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { int32_t ret = HITLS_SUCCESS; uint16_t index = 0; uint8_t psk[HS_PSK_MAX_LEN] = {0}; ListHead *node = NULL; ListHead *tmpNode = NULL; PreSharedKey *cur = NULL; PreSharedKey *offeredPsks = clientHello->extension.content.preSharedKey; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(offeredPsks->pskNode)) { uint32_t pskLen = HS_PSK_MAX_LEN; cur = LIST_ENTRY(node, PreSharedKey, pskNode); ret = ServerFindPsk(ctx, cur, psk, &pskLen); if (ret != HITLS_SUCCESS) { return ret; } if (pskLen == 0) { index++; /* The corresponding psk cannot be found. Search for the next psk */ continue; } /* An available psk is found */ ret = Tls13ServerSetPskInfo(ctx, psk, pskLen, index); if (ret != HITLS_SUCCESS) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); /* Clear sensitive memory */ return ret; } ret = CompareBinder(ctx, cur, psk, pskLen, clientHello->truncateHelloLen); (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); /* Clear sensitive memory */ if (ret != HITLS_SUCCESS) { /* RFC8446 Section 6.2:decrypt_error: A handshake (not record layer) cryptographic operation failed, including being unable to correctly verify a signature or validate a Finished message or a PSK binder. */ ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECRYPT_ERROR); return ret; } cur->isValid = true; break; } return ret; } #endif static int32_t Tls13ServerSetSessionId(TLS_Ctx *ctx, const uint8_t *sessionId, uint32_t sessionIdSize) { if (sessionIdSize == 0) { ctx->hsCtx->sessionIdSize = sessionIdSize; return HITLS_SUCCESS; } uint8_t *tmpSession = BSL_SAL_Dump(sessionId, sessionIdSize); if (tmpSession == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15248, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc sessionId fail when process client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } BSL_SAL_FREE(ctx->hsCtx->sessionId); // Clearing old memory ctx->hsCtx->sessionId = tmpSession; ctx->hsCtx->sessionIdSize = sessionIdSize; return HITLS_SUCCESS; } static int32_t Tls13ServerCheckClientHelloExtension(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { do { /* If not containing a "pre_shared_key" extension, it MUST contain both a "signature_algorithms" extension and a "supported_groups" extension. */ if ((!clientHello->extension.flag.havePreShareKey) && (!clientHello->extension.flag.haveSignatureAlgorithms || !clientHello->extension.flag.haveSupportedGroups)) { break; } /* If containing a "supported_groups" extension, it MUST also contain a "key_share" extension, and vice versa. */ if ((clientHello->extension.flag.haveSupportedGroups && !clientHello->extension.flag.haveKeyShare) || (!clientHello->extension.flag.haveSupportedGroups && clientHello->extension.flag.haveKeyShare)) { break; } /* A client MUST provide a "psk_key_exchange_modes" extension if it offers a "pre_shared_key" extension. */ if (clientHello->extension.flag.havePreShareKey && !clientHello->extension.flag.havePskExMode) { break; } // with psk && psk mode is dhe && without keyshare uint32_t clientKeMode = GetClientKeMode(&clientHello->extension.content); if (clientHello->extension.flag.havePreShareKey && (clientKeMode & TLS13_KE_MODE_PSK_WITH_DHE) == TLS13_KE_MODE_PSK_WITH_DHE && !clientHello->extension.flag.haveKeyShare) { break; } return HITLS_SUCCESS; } while (false); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_MISSING_EXTENSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16139, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid client hello: missing extension.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_MISSING_EXTENSION); return HITLS_MSG_HANDLE_MISSING_EXTENSION; } static int32_t Tls13ServerCheckSecondClientHello(TLS_Ctx *ctx, ClientHelloMsg *clientHello) { if (ctx->hsCtx->haveHrr) { if (ctx->hsCtx->firstClientHello->cipherSuitesSize != clientHello->cipherSuitesSize || memcmp(ctx->hsCtx->firstClientHello->cipherSuites, clientHello->cipherSuites, clientHello->cipherSuitesSize * sizeof(uint16_t)) != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17062, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "Server's cipher suites do not match client's cipher suite.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE; } return HITLS_SUCCESS; } if (ctx->hsCtx->firstClientHello != NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17063, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_INTERNAL_EXCEPTION; } ctx->hsCtx->firstClientHello = (ClientHelloMsg *)BSL_SAL_Dump(clientHello, sizeof(ClientHelloMsg)); if (ctx->hsCtx->firstClientHello == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16147, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "clientHello malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } clientHello->refCnt = 1; return HITLS_SUCCESS; } static int32_t Tls13ServerCheckCompressionMethods(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { if (clientHello->compressionMethodsSize != 1u) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16162, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the compression length of client hello is incorrect.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD; } /* If the compression method list contains no compression, return success */ // If the compression method contains no compression (0), a parsing success message is returne if (clientHello->compressionMethods[0] == 0u) { return HITLS_SUCCESS; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16163, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "can not find a appropriate compression method in client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD; } static int32_t Tls13ServerBasicCheckClientHello(TLS_Ctx *ctx, ClientHelloMsg *clientHello) { int32_t ret = Tls13ServerCheckSecondClientHello(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } /* Set the negotiated version number */ ctx->negotiatedInfo.version = HITLS_VERSION_TLS13; ret = Tls13ServerCheckCompressionMethods(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } /* Copy random numbers */ ret = memcpy_s(ctx->hsCtx->clientRandom, HS_RANDOM_SIZE, clientHello->randomValue, HS_RANDOM_SIZE); if (ret != EOK) { return ret; } /* Copy the session ID */ ret = Tls13ServerSetSessionId(ctx, clientHello->sessionId, clientHello->sessionIdSize); if (ret != HITLS_SUCCESS) { return ret; } return ServerSelectCipherSuite(ctx, clientHello); } static int32_t Tls13ServerSelectCert(TLS_Ctx *ctx, const ClientHelloMsg *clientHello) { /* If a PSK exists, no certificate needs to be sent regardless of whether the PSK is psk_only or psk_with_dhe */ if (ctx->hsCtx->kxCtx->pskInfo13.psk != NULL) { return HITLS_SUCCESS; } /* rfc 8446 4.2.3. If the client does not provide the signature algorithm extension, an alert message must be sent. */ if (clientHello->extension.content.signatureAlgorithms == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17065, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "miss signatureAlgorithms extension", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_MISSING_EXTENSION); return HITLS_MSG_HANDLE_MISSING_EXTENSION; } CERT_ExpectInfo expectCertInfo = {0}; expectCertInfo.certType = CERT_TYPE_UNKNOWN; /* Do not specify the certificate type */ expectCertInfo.signSchemeList = clientHello->extension.content.signatureAlgorithms; expectCertInfo.signSchemeNum = clientHello->extension.content.signatureAlgorithmsSize; /* Only the uncompressed format is supported */ uint8_t pointFormat = HITLS_POINT_FORMAT_UNCOMPRESSED; expectCertInfo.ecPointFormatList = &pointFormat; expectCertInfo.ecPointFormatNum = 1u; int32_t ret = SAL_CERT_SelectCertByInfo(ctx, &expectCertInfo); if (ret != HITLS_SUCCESS) { /* No proper certificate */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15219, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "have no suitable cert. ret %d", ret, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE; } return HITLS_SUCCESS; } static int32_t Tls13ServerCheckClientHello(TLS_Ctx *ctx, ClientHelloMsg *clientHello, bool *isNeedSendHrr) { uint32_t selectKeMode = 0; int32_t ret = Tls13ServerBasicCheckClientHello(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } /* rfc8446 9.2. Mandatory-to-Implement Extensions */ ret = Tls13ServerCheckClientHelloExtension(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } uint32_t clientKeMode = GetClientKeMode(&clientHello->extension.content); selectKeMode = clientKeMode & ctx->config.tlsConfig.keyExchMode; #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_FEATURE_PSK) if (clientHello->extension.flag.havePreShareKey && selectKeMode != 0) { /* calculate the binder value and compare it with the received binder value. */ ret = ServerSelectPskAndCheckBinder(ctx, clientHello); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_PSK_INVALID); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15940, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ServerSelectPskAndCheckBinder failed. ret %d", ret, 0, 0, 0); return HITLS_MSG_HANDLE_PSK_INVALID; } } #endif if (ctx->hsCtx->kxCtx->pskInfo13.psk == NULL || (selectKeMode & TLS13_KE_MODE_PSK_WITH_DHE) == TLS13_KE_MODE_PSK_WITH_DHE) { ret = Tls13ServerProcessKeyShare(ctx, clientHello, isNeedSendHrr); /* The group has been selected during the cipher suite selection. Therefore, the keyshare can be processed here */ if (ret != HITLS_SUCCESS) { return ret; } } #ifdef HITLS_TLS_FEATURE_SNI /* The message contains a server_name extension with the length greater than 0 */ ret = ServerDealServerName(ctx, clientHello); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_SNI */ return ret; } static int32_t Tls13ServerPostCheckClientHello(TLS_Ctx *ctx, ClientHelloMsg *clientHello, bool *isNeedSendHrr) { int32_t ret; #ifdef HITLS_TLS_FEATURE_CERT_CB ret = ProcessCertCallback(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CERT_CB */ ret = ProcessClientHelloExt(ctx, clientHello, (*isNeedSendHrr)); if (ret != HITLS_SUCCESS) { return ret; } return Tls13ServerSelectCert(ctx, clientHello); } static int32_t CheckSupportVersion(TLS_Ctx *ctx, uint16_t version, uint16_t *selectVersion) { if (version >= HITLS_VERSION_TLS13 && !IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { version = HITLS_VERSION_TLS12; } uint32_t versionBits = MapVersion2VersionBit(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), version); #ifdef HITLS_TLS_PROTO_TLCP11 if (((version > HITLS_VERSION_SSL30) || (version == HITLS_VERSION_TLCP_DTLCP11)) && #else if ((version > HITLS_VERSION_SSL30) && #endif /* HITLS_TLS_PROTO_TLCP11 */ ((versionBits & ctx->config.tlsConfig.version) == versionBits)) { *selectVersion = version; return HITLS_SUCCESS; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17066, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "negotiate version fail", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } bool IsTls13KeyExchAvailable(TLS_Ctx *ctx) { TLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *certMgrCtx = config->certMgrCtx; #ifdef HITLS_TLS_FEATURE_PSK if (config->pskServerCb != NULL) { return true; } if (config->pskFindSessionCb != NULL) { return true; } #endif /* HITLS_TLS_FEATURE_PSK */ /* The PSK is not used. The certificate must be set */ BSL_HASH_Hash *certPairs = certMgrCtx->certPairs; BSL_HASH_Iterator it = BSL_HASH_IterBegin(certPairs); while (it != BSL_HASH_IterEnd(certPairs)) { uint32_t keyType = (uint32_t)BSL_HASH_HashIterKey(certPairs, it); if (keyType == TLS_CERT_KEY_TYPE_DSA) { /* in TLS1.3, Do not use the DSA certificate. */ it = BSL_HASH_IterNext(certPairs, it); continue; } CERT_Pair *certPair = (CERT_Pair *)BSL_HASH_IterValue(certPairs, it); if (certPair != NULL && certPair->cert != NULL && certPair->privateKey != NULL) { return true; } it = BSL_HASH_IterNext(certPairs, it); } return false; } static int32_t SelectVersion(TLS_Ctx *ctx, const ClientHelloMsg *clientHello, uint16_t *selectVersion) { int32_t ret; uint16_t version = clientHello->version; /** * According to rfc8446 section 4.2.1 if the ClientHello does not have the supportedVersions extension, * Then the server must negotiate TLS 1.2 or earlier as specified in rfc5246. */ if (clientHello->extension.content.supportedVersionsCount == 0) { ret = CheckSupportVersion(ctx, version, selectVersion); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16134, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server cannot negotiate a version.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); } return ret; } /* If the received message is not an earlier version, the version byte in the tls1.3 must be 0x0303 according to * section 4.1.2 in RFC 8446 */ if (version != HITLS_VERSION_TLS12) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15249, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "illegal client legacy_version(0x%02x).", version, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } uint32_t versionBits; uint16_t versions[] = {HITLS_VERSION_DTLS12, HITLS_VERSION_TLS13, HITLS_VERSION_TLS12, HITLS_VERSION_TLCP_DTLCP11}; /* Find the supported version in the extended field supportedVersions. */ for (uint32_t j = 0; j < sizeof(versions) / sizeof(uint16_t); j++) { version = versions[j]; /* Check whether the version is supported */ for (int i = 0; i < clientHello->extension.content.supportedVersionsCount; i++) { versionBits = MapVersion2VersionBit(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), version); if (clientHello->extension.content.supportedVersions[i] != version || (versionBits & ctx->config.tlsConfig.version) == 0) { continue; } if (((version == HITLS_VERSION_TLS13) && (!IsTls13KeyExchAvailable(ctx)))) { /* TLS1.3 must have an available PSK or certificate, and TLS1.3 cannot negotiate SSL versions earlier * than SSL3.0. */ continue; } /* rfc8446 4.2.1 The server must be ready to receive ClientHello that contains the supportedVersions * extension but does not contain 0x0304 in the version list, Therefore, if a matching version is found, * even if the version is an earlier version, the system directly returns */ *selectVersion = version; return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15250, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server cannot negotiate a version.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } static int32_t UpdateServerBaseKeyExMode(TLS_Ctx *ctx) { uint32_t tls13BasicKeyExMode = 0; KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; if (kxCtx->pskInfo13.psk != NULL && kxCtx->peerPubkey != NULL) { tls13BasicKeyExMode = TLS13_KE_MODE_PSK_WITH_DHE; } else if (kxCtx->pskInfo13.psk != NULL) { tls13BasicKeyExMode = TLS13_KE_MODE_PSK_ONLY; } else if (kxCtx->peerPubkey != NULL) { tls13BasicKeyExMode = TLS13_CERT_AUTH_WITH_DHE; } else { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17067, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "psk and peerPubkey are null", 0, 0, 0, 0); // kxCtx->pskInfo13.psk == NULL && kxCtx->peerPubkey == NULL 由Tls13ServerCheckClientHello保证不会在此出现 BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } ctx->negotiatedInfo.tls13BasicKeyExMode = tls13BasicKeyExMode; return HITLS_SUCCESS; } static int32_t Tls13ServerProcessClientHello(TLS_Ctx *ctx, HS_Msg *msg) { int32_t ret = HITLS_SUCCESS; ClientHelloMsg *clientHello = &msg->body.clientHello; /* An unencrypted CCS may be received after sending or receiving the first ClientHello according to RFC 8446 */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); bool isNeedSendHrr = false; /* Processing Client Hello Packets */ if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_A) { ret = Tls13ServerCheckClientHello(ctx, clientHello, &isNeedSendHrr); if (ret != HITLS_SUCCESS) { return ret; } ctx->hsCtx->readSubState = TLS_PROCESS_STATE_B; } if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_B) { ret = Tls13ServerPostCheckClientHello(ctx, clientHello, &isNeedSendHrr); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17056, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PostProcessClientHello fail.", 0, 0, 0, 0); return ret; } if (isNeedSendHrr) { return HS_ChangeState(ctx, TRY_SEND_HELLO_RETRY_REQUEST); } ret = UpdateServerBaseKeyExMode(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #ifdef HITLS_TLS_FEATURE_PHA TLS_Config *tlsConfig = &ctx->config.tlsConfig; if (ctx->phaState == PHA_NONE && tlsConfig->isSupportClientVerify && tlsConfig->isSupportPostHandshakeAuth && msg->body.clientHello.extension.flag.havePostHsAuth) { ctx->phaState = PHA_EXTENSION; } #endif /* HITLS_TLS_FEATURE_PHA */ return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO); } int32_t Tls13ServerRecvClientHelloProcess(TLS_Ctx *ctx, HS_Msg *msg) { int32_t ret = 0; uint16_t selectedVersion = 0; ClientHelloMsg *clientHello = &msg->body.clientHello; if (ctx->hsCtx->readSubState == TLS_PROCESS_STATE_A) { #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB /* Perform the ClientHello callback. The pause handshake status is not considered */ ret = ClientHelloCbCheck(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */ ret = SelectVersion(ctx, clientHello, &selectedVersion); if (ret != HITLS_SUCCESS) { return ret; } /* If the TLS version is earlier than 1.3, the ServerHello.version parameter must be set on the server and the * supported_versions extension cannot be sent */ clientHello->version = selectedVersion; } switch (clientHello->version) { #ifdef HITLS_TLS_PROTO_TLS_BASIC case HITLS_VERSION_TLS12: BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15251, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "tls1.3 server receive a 0x%x clientHello.", selectedVersion, 0, 0, 0); return Tls12ServerRecvClientHelloProcess(ctx, msg, false); #endif /* HITLS_TLS_PROTO_TLS_BASIC */ case HITLS_VERSION_TLS13: return Tls13ServerProcessClientHello(ctx, msg); default: break; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15252, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server select an unsupported version.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/recv/src/recv_client_hello.c
C
unknown
97,423
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs.h" #include "hs_ctx.h" #include "hs_kx.h" #include "hs_msg.h" #include "hs_verify.h" #include "hs_common.h" #include "securec.h" #include "bsl_sal.h" #ifdef HITLS_TLS_FEATURE_PSK static int32_t RetriveServerPsk(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg) { uint8_t psk[HS_PSK_MAX_LEN] = {0}; if ((!IsPskNegotiation(ctx)) == true) { return HITLS_SUCCESS; } if (ctx->config.tlsConfig.pskServerCb == NULL) { BSL_ERR_PUSH_ERROR(HITLS_UNREGISTERED_CALLBACK); return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID17068, "unregistered pskServerCb"); } uint32_t pskUsedLen = ctx->config.tlsConfig.pskServerCb(ctx, clientKxMsg->pskIdentity, psk, HS_PSK_MAX_LEN); if (pskUsedLen == 0 || pskUsedLen > HS_PSK_MAX_LEN) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN, BINLOG_ID17069, "pskUsedLen incorrect"); } if (ctx->hsCtx->kxCtx->pskInfo == NULL) { ctx->hsCtx->kxCtx->pskInfo = (PskInfo *)BSL_SAL_Calloc(1u, sizeof(PskInfo)); if (ctx->hsCtx->kxCtx->pskInfo == NULL) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17070, "Calloc fail"); } } uint8_t *tmpIdentity = NULL; if (clientKxMsg->pskIdentity != NULL) { tmpIdentity = (uint8_t *)BSL_SAL_Calloc(1u, (clientKxMsg->pskIdentitySize + 1) * sizeof(uint8_t)); if (tmpIdentity == NULL) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17071, "Calloc fail"); } (void)memcpy_s(tmpIdentity, clientKxMsg->pskIdentitySize + 1, clientKxMsg->pskIdentity, clientKxMsg->pskIdentitySize); BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo->identity); ctx->hsCtx->kxCtx->pskInfo->identity = tmpIdentity; ctx->hsCtx->kxCtx->pskInfo->identityLen = clientKxMsg->pskIdentitySize; } uint8_t *tmpPsk = (uint8_t *)BSL_SAL_Dump(psk, pskUsedLen); if (tmpPsk == NULL) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17072, "Dump fail"); } BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo->psk); ctx->hsCtx->kxCtx->pskInfo->psk = tmpPsk; ctx->hsCtx->kxCtx->pskInfo->pskLen = pskUsedLen; /* sensitive info cleanup */ (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PSK */ static int32_t ProcessClientKxMsg(TLS_Ctx *ctx, const ClientKeyExchangeMsg *clientKxMsg) { HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_PSK ret = RetriveServerPsk(ctx, clientKxMsg); if (ret != HITLS_SUCCESS) { // log here return ret; } #endif /* HITLS_TLS_FEATURE_PSK */ /** Process the key exchange packet from the client */ switch (hsCtx->kxCtx->keyExchAlgo) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: /* ECDHE of TLCP is also in this branch */ case HITLS_KEY_EXCH_ECDHE_PSK: ret = HS_ProcessClientKxMsgEcdhe(ctx, clientKxMsg); break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = HS_ProcessClientKxMsgDhe(ctx, clientKxMsg); break; #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_SUITE_KX_RSA case HITLS_KEY_EXCH_RSA: case HITLS_KEY_EXCH_RSA_PSK: ret = HS_ProcessClientKxMsgRsa(ctx, clientKxMsg); break; #endif /* HITLS_TLS_SUITE_KX_RSA */ case HITLS_KEY_EXCH_PSK: ret = HITLS_SUCCESS; break; #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: ret = HS_ProcessClientKxMsgSm2(ctx, clientKxMsg); break; #endif default: BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17073, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unknow keyExchAlgo", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG); ret = HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG; ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); break; } return ret; } static int32_t GenerateKeyMaterial(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = HITLS_SUCCESS; /** Obtain the server information */ const ClientKeyExchangeMsg *clientKxMsg = &msg->body.clientKeyExchange; ret = ProcessClientKxMsg(ctx, clientKxMsg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15820, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server process client key exchange msg fail.", 0, 0, 0, 0); return ret; } ret = HS_GenerateMasterSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15821, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server generate master secret fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } /** Server secret derivation */ ret = HS_KeyEstablish(ctx, ctx->isClient); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15822, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server key establish fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) ret = HS_SetSctpAuthKey(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17074, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "SetSctpAuthKey fail", 0, 0, 0, 0); } #endif /* HITLS_TLS_PROTO_DTLS12 */ return ret; } int32_t ServerRecvClientKxProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = HITLS_SUCCESS; /** Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; ret = GenerateKeyMaterial(ctx, msg); if (ret != HITLS_SUCCESS) { return ret; } /** * According to RFC 5246 7.4.8: This message (referred to here as client cert verify) is only sent following * a client certificate that has signing capability. * In the case of dual-ended parity * 1) If the peer certificate is not empty, the system calculates the signature and switches to the cert verify * state. 2) If the peer certificate is empty, the client sends an empty certificate message after the server sends * a cert request message, In this case, the client does not send the cert verify message. Therefore, the client * needs to switch to the state of receiving the Finish message. */ if (hsCtx->isNeedClientCert && hsCtx->peerCert != NULL) { return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE_VERIFY); } ret = VERIFY_CalcVerifyData(ctx, true, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15823, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server Calculate client finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); (void)memset_s(ctx->hsCtx->masterKey, sizeof(ctx->hsCtx->masterKey), 0, sizeof(ctx->hsCtx->masterKey)); return ret; } ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/recv/src/recv_client_key_exchange.c
C
unknown
8,789
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_TLS13 #ifdef HITLS_TLS_HOST_CLIENT #include <stdint.h> #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "record.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_extensions.h" #include "hs_msg.h" #include "hs_verify.h" #include "alpn.h" typedef int32_t (*CheckEncryptedExtFunc)(TLS_Ctx *ctx, const EncryptedExtensions *eEMsg); #ifdef HITLS_TLS_FEATURE_SNI static int32_t Tls13ClientCheckServerName(TLS_Ctx *ctx, const EncryptedExtensions *eEMsg) { if ((ctx->hsCtx->extFlag.haveServerName == false) && (eEMsg->haveServerName == true)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16200, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send server_name but get extended server_name .", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } /* Receive empty server_name extension */ if ((ctx->hsCtx->extFlag.haveServerName == true) && (eEMsg->haveServerName == true)) { /* Not in session resumption and the client has previously sent the server_name extension */ if (ctx->session == NULL && ctx->config.tlsConfig.serverName != NULL && ctx->config.tlsConfig.serverNameSize > 0) { /* Indicates server negotiated the server_name extension in client successfully */ ctx->negotiatedInfo.isSniStateOK = true; ctx->hsCtx->serverNameSize = ctx->config.tlsConfig.serverNameSize; BSL_SAL_FREE(ctx->hsCtx->serverName); ctx->hsCtx->serverName = (uint8_t *)BSL_SAL_Dump(ctx->config.tlsConfig.serverName, ctx->hsCtx->serverNameSize * sizeof(uint8_t)); if (ctx->hsCtx->serverName == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17075, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SNI */ #ifdef HITLS_TLS_FEATURE_ALPN static int32_t Tls13ClientCheckNegotiatedAlpn(TLS_Ctx *ctx, const EncryptedExtensions *eEMsg) { return ClientCheckNegotiatedAlpn( ctx, eEMsg->haveSelectedAlpn, eEMsg->alpnSelected, eEMsg->alpnSelectedSize); } #endif static int32_t ClientCheckEncryptedExtensionsFlag(TLS_Ctx *ctx, const EncryptedExtensions *eEMsg) { static const CheckEncryptedExtFunc EXT_INFO_LIST[] = { #ifdef HITLS_TLS_FEATURE_SNI Tls13ClientCheckServerName, #endif /* HITLS_TLS_FEATURE_SNI */ #ifdef HITLS_TLS_FEATURE_ALPN Tls13ClientCheckNegotiatedAlpn, #endif NULL, }; int32_t ret; ret = HS_CheckReceivedExtension(ctx, ENCRYPTED_EXTENSIONS, eEMsg->extensionTypeMask, HS_EX_TYPE_TLS1_3_ALLOWED_OF_ENCRYPTED_EXTENSIONS); if (ret != HITLS_SUCCESS) { return ret; } for (uint32_t i = 0; i < sizeof(EXT_INFO_LIST) / sizeof(EXT_INFO_LIST[0]); i++) { if (EXT_INFO_LIST[i] == NULL) { continue; } ret = EXT_INFO_LIST[i](ctx, eEMsg); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } int32_t Tls13ClientRecvEncryptedExtensionsProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret; const EncryptedExtensions *eEMsg = &msg->body.encryptedExtensions; // Process the extension. ret = ClientCheckEncryptedExtensionsFlag(ctx, eEMsg); if (ret != HITLS_SUCCESS) { return ret; } /* In psk_only mode, the 'server verify data' needs to be calculated * for verifying the 'finished' message from the server. */ PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; if ((pskInfo->psk != NULL)) { ret = VERIFY_Tls13CalcVerifyData(ctx, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15856, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client calculate server finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } return HS_ChangeState(ctx, TRY_RECV_FINISH); } return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE_REQUEST); } #endif /* HITLS_TLS_HOST_CLIENT */ #endif /* HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/recv/src/recv_encrypted_extensions.c
C
unknown
5,082
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_log.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "hitls_error.h" #include "rec.h" #include "tls.h" #include "hs_ctx.h" #include "hs_verify.h" #include "hs_common.h" #include "hs_verify.h" #include "recv_process.h" #include "hs_kx.h" #ifdef HITLS_TLS_FEATURE_SESSION #include "session_mgr.h" #endif #ifdef HITLS_TLS_FEATURE_SESSION #ifdef HITLS_TLS_FEATURE_SESSION_TICKET static int32_t SetSessionTicketInfo(TLS_Ctx *ctx) { int32_t ret = 0; HS_Ctx *hsCtx = ctx->hsCtx; BSL_SAL_FREE(hsCtx->sessionId); hsCtx->sessionIdSize = 0; if (hsCtx->ticketSize == 0) { return HITLS_SUCCESS; } if (ctx->isClient) { uint8_t sessionId[HITLS_SESSION_ID_MAX_SIZE]; ret = SESSMGR_GernerateSessionId(ctx, sessionId, HITLS_SESSION_ID_MAX_SIZE); if (ret != HITLS_SUCCESS) { return ret; } HITLS_SESS_SetSessionId(ctx->session, sessionId, HITLS_SESSION_ID_MAX_SIZE); } ret = SESS_SetTicket(ctx->session, hsCtx->ticket, hsCtx->ticketSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15970, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Session set ticket fail.", 0, 0, 0, 0); } return ret; } #endif int32_t SetSessionTicketAndSessionID(TLS_Ctx *ctx, bool isTls13) { int32_t ret = HITLS_SUCCESS; (void)ctx; (void)isTls13; #ifdef HITLS_TLS_FEATURE_SESSION_TICKET if (ctx->negotiatedInfo.isTicket && !isTls13) { ret = SetSessionTicketInfo(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #endif #ifdef HITLS_TLS_FEATURE_SESSION_ID /* The default session length is 0. If the session length is not 0, insert the session length */ if (ctx->hsCtx->sessionIdSize != 0 && !isTls13) { /* The session generated during the finish operation of TLS 1.3 cannot be used for session resume. In this * case, sessionId is blocked so that the HITLS_SESS_IsResumable return value is false */ ret = HITLS_SESS_SetSessionId(ctx->session, ctx->hsCtx->sessionId, ctx->hsCtx->sessionIdSize); if (ret != HITLS_SUCCESS) { return ret; } } ret = HITLS_SESS_SetSessionIdCtx( ctx->session, ctx->config.tlsConfig.sessionIdCtx, ctx->config.tlsConfig.sessionIdCtxSize); if (ret != HITLS_SUCCESS) { return ret; } #endif return ret; } static int32_t SessionConfig(TLS_Ctx *ctx) { int32_t ret = 0; bool isTls13 = (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13); HS_Ctx *hsCtx = ctx->hsCtx; ret = SetSessionTicketAndSessionID(ctx, isTls13); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_SNI /* When the SNI negotiation is HITLS_ACCEPT_ERR_OK, save the client Hello server_name extension to the session * structure */ if (ctx->negotiatedInfo.isSniStateOK && isTls13 == false) { ret = SESS_SetHostName(ctx->session, hsCtx->serverNameSize, hsCtx->serverName); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17076, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SetHostName fail", 0, 0, 0, 0); return ret; } } #endif /* HITLS_TLS_FEATURE_SNI */ (void)HITLS_SESS_SetProtocolVersion(ctx->session, ctx->negotiatedInfo.version); (void)HITLS_SESS_SetCipherSuite(ctx->session, ctx->negotiatedInfo.cipherSuiteInfo.cipherSuite); uint32_t masterKeySize = MASTER_SECRET_LEN; #ifdef HITLS_TLS_PROTO_TLS13 if (isTls13) { masterKeySize = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (masterKeySize == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17077, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize fail", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } } #endif ret = HITLS_SESS_SetMasterKey(ctx->session, hsCtx->masterKey, masterKeySize); if (ret != HITLS_SUCCESS) { return ret; } ret = HITLS_SESS_SetHaveExtMasterSecret(ctx->session, (uint8_t)ctx->negotiatedInfo.isExtendedMasterSecret); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_TLS_CONNECTION_INFO_NEGOTIATION) && defined(HITLS_TLS_FEATURE_SESSION) if (ctx->config.tlsConfig.isKeepPeerCert) { ret = SESS_SetPeerCert(ctx->session, hsCtx->peerCert, ctx->isClient); if (ret != HITLS_SUCCESS) { return ret; } hsCtx->peerCert = NULL; } #endif /* HITLS_TLS_CONNECTION_INFO_NEGOTIATION && HITLS_TLS_FEATURE_SESSION */ return HITLS_SUCCESS; } static int32_t HsSetSessionInfo(TLS_Ctx *ctx) { int32_t ret = 0; TLS_SessionMgr *sessMgr = ctx->config.tlsConfig.sessMgr; SESSMGR_ClearTimeout(sessMgr); /* This parameter is not required for session multiplexing */ if (ctx->negotiatedInfo.isResume == true) { return HITLS_SUCCESS; } HITLS_SESS_Free(ctx->session); ctx->session = HITLS_SESS_New(); if (ctx->session == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15893, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Session malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } uint64_t timeout = SESSMGR_GetTimeout(sessMgr); #ifdef HITLS_TLS_FEATURE_SESSION_TICKET timeout = ctx->hsCtx->ticketLifetimeHint == 0 ? timeout : ctx->hsCtx->ticketLifetimeHint; #endif HITLS_SESS_SetTimeout(ctx->session, timeout); ret = SessionConfig(ctx); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) /* The session cache does not store TLS1.3 sessions */ if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { SESSMGR_InsertSession(sessMgr, ctx->session, ctx->isClient); if (ctx->globalConfig != NULL && ctx->globalConfig->newSessionCb != NULL) { HITLS_SESS_UpRef(ctx->session); // It is convenient for users to take away and needs to be released by users if (ctx->globalConfig->newSessionCb(ctx, ctx->session) == 0) { /* If the user does not reference the session, the number of reference times decreases by 1 */ HITLS_SESS_Free(ctx->session); } } } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION */ int32_t CheckFinishedVerifyData(const FinishedMsg *finishedMsg, const uint8_t *verifyData, uint32_t verifyDataSize) { if ((finishedMsg->verifyDataSize == 0u) || (verifyDataSize == 0u)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15737, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Finished data len cannot be zero.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN; } if (finishedMsg->verifyDataSize != verifyDataSize) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15738, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Finished data len unequal.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN; } if (memcmp(finishedMsg->verifyData, verifyData, verifyDataSize) != 0) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15739, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Finished data unequal.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_HOST_CLIENT int32_t ClientRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = 0; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; VerifyCtx *verifyCtx = hsCtx->verifyCtx; const FinishedMsg *finished = &msg->body.finished; uint8_t verifyData[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataSize = MAX_DIGEST_SIZE; ret = VERIFY_GetVerifyData(verifyCtx, verifyData, &verifyDataSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15740, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client get server finished verify data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ret = CheckFinishedVerifyData(finished, verifyData, verifyDataSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15741, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client verify server finished data error.", 0, 0, 0, 0); if (ret == HITLS_MSG_HANDLE_INCORRECT_DIGEST_LEN) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); } else { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECRYPT_ERROR); } return HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL; } #ifdef HITLS_TLS_FEATURE_SESSION ret = HsSetSessionInfo(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15895, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set session information failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #endif /* HITLS_TLS_FEATURE_SESSION */ /* CCS messages are not allowed to be received later. */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS_BASIC int32_t Tls12ClientRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = ClientRecvFinishedProcess(ctx, msg); if (ret != HITLS_SUCCESS) { return ret; } if (ctx->negotiatedInfo.isResume == true) { ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsClientRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { #ifdef HITLS_BSL_UIO_UDP if (ctx->preState == CM_STATE_TRANSPORTING && ctx->state == CM_STATE_HANDSHAKING) { int32_t ret = REC_RetransmitListFlush(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15888, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "recv post hs finished, send retransmit msg.", 0, 0, 0, 0); return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_BSL_UIO_UDP */ int32_t ret = ClientRecvFinishedProcess(ctx, msg); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_BSL_UIO_UDP /* Clear the retransmission queue */ REC_RetransmitListClean(ctx->recCtx); #endif /* HITLS_BSL_UIO_UDP */ if (ctx->negotiatedInfo.isResume == true) { ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } return HS_ChangeState(ctx, TLS_CONNECTED); } #endif #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13ClientRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = ClientRecvFinishedProcess(ctx, msg); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_TLS13CalcServerFinishProcessSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17078, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcServerFinishProcessSecret fail", 0, 0, 0, 0); return ret; } /* Activate serverAppTrafficSecret to decrypt the App data sent by the server */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); ret = HS_SwitchTrafficKey(ctx, ctx->serverAppTrafficSecret, hashLen, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17079, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SwitchTrafficKey fail", 0, 0, 0, 0); return ret; } if (ctx->hsCtx->isNeedClientCert) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE); } return HS_ChangeState(ctx, TRY_SEND_FINISH); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER int32_t ServerRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = 0; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; VerifyCtx *verifyCtx = hsCtx->verifyCtx; uint8_t verifyData[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataSize = MAX_DIGEST_SIZE; const FinishedMsg *finished = &msg->body.finished; ret = VERIFY_GetVerifyData(verifyCtx, verifyData, &verifyDataSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15742, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server get client finished verify data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ret = CheckFinishedVerifyData(finished, verifyData, verifyDataSize); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15743, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server verify client finished data error.", 0, 0, 0, 0); if (ret == HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECRYPT_ERROR); } else { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); } return HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL; } #ifdef HITLS_TLS_FEATURE_SESSION ret = HsSetSessionInfo(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15897, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set session information failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #endif /* HITLS_TLS_FEATURE_SESSION */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS_BASIC int32_t Tls12ServerRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = ServerRecvFinishedProcess(ctx, msg); if (ret != HITLS_SUCCESS) { return ret; } if (ctx->negotiatedInfo.isResume == true) { ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); return HS_ChangeState(ctx, TLS_CONNECTED); } if (ctx->negotiatedInfo.isTicket == true) { return HS_ChangeState(ctx, TRY_SEND_NEW_SESSION_TICKET); } return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsServerRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { #ifdef HITLS_BSL_UIO_UDP if (ctx->preState == CM_STATE_TRANSPORTING && ctx->state == CM_STATE_HANDSHAKING) { int32_t ret = REC_RetransmitListFlush(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15885, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "recv post hs finished, send retransmit msg.", 0, 0, 0, 0); return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_BSL_UIO_UDP */ int32_t ret = ServerRecvFinishedProcess(ctx, msg); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_BSL_UIO_UDP /* Clear the retransmission queue */ REC_RetransmitListClean(ctx->recCtx); #endif /* HITLS_BSL_UIO_UDP */ #ifdef HITLS_TLS_FEATURE_SESSION if (ctx->negotiatedInfo.isResume == true) { ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_FEATURE_SESSION */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET if (ctx->negotiatedInfo.isTicket == true) { return HS_ChangeState(ctx, TRY_SEND_NEW_SESSION_TICKET); } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } #endif #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13ServerRecvFinishedProcess(TLS_Ctx *ctx, const HS_Msg *msg) { /** CCS messages are not allowed to be received */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); ctx->plainAlertForbid = true; int32_t ret = ServerRecvFinishedProcess(ctx, msg); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState == PHA_REQUESTED) { ctx->phaState = PHA_EXTENSION; } else #endif /* HITLS_TLS_FEATURE_PHA */ { /* Switch Application Traffic Secret */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); ret = HS_SwitchTrafficKey(ctx, ctx->clientAppTrafficSecret, hashLen, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17080, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SwitchTrafficKey fail", 0, 0, 0, 0); return ret; } ret = HS_TLS13DeriveResumptionMasterSecret(ctx); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState == PHA_EXTENSION && ctx->config.tlsConfig.isSupportClientVerify && ctx->config.tlsConfig.isSupportPostHandshakeAuth) { SAL_CRYPT_DigestFree(ctx->phaHash); ctx->phaHash = SAL_CRYPT_DigestCopy(ctx->hsCtx->verifyCtx->hashCtx); if (ctx->phaHash == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_DIGEST); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16176, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pha hash copy error: digest copy fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } } #endif /* HITLS_TLS_FEATURE_PHA */ } #ifdef HITLS_TLS_FEATURE_SESSION_TICKET /* When ticketNums is 0, no ticket is sent */ if (ctx->hsCtx->sentTickets < ctx->config.tlsConfig.ticketNums) { return HS_ChangeState(ctx, TRY_SEND_NEW_SESSION_TICKET); } #endif return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/recv/src/recv_finished.c
C
unknown
18,774
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #ifdef HITLS_TLS_PROTO_DTLS12 #include "securec.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "tls_binlog_id.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "rec.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_common.h" int32_t DtlsClientRecvHelloVerifyRequestProcess(TLS_Ctx *ctx, HS_Msg *msg) { TLS_NegotiatedInfo *negotiatedInfo = &ctx->negotiatedInfo; HelloVerifyRequestMsg *helloVerifyReq = &msg->body.helloVerifyReq; /* release the old cookie first */ BSL_SAL_FREE(negotiatedInfo->cookie); /* allow zero-length cookies to be received */ if (helloVerifyReq->cookieLen != 0) { negotiatedInfo->cookie = (uint8_t *)BSL_SAL_Dump(helloVerifyReq->cookie, helloVerifyReq->cookieLen); if (negotiatedInfo->cookie == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16080, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cookie malloc fail when process hello verify request.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } } negotiatedInfo->cookieSize = helloVerifyReq->cookieLen; #ifdef HITLS_BSL_UIO_UDP /* clear the retransmission queue */ REC_RetransmitListClean(ctx->recCtx); #endif /* HITLS_BSL_UIO_UDP */ return HS_ChangeState(ctx, TRY_SEND_CLIENT_HELLO); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/recv/src/recv_hello_verify_request.c
C
unknown
2,037
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_SESSION_TICKET #include <stdint.h> #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_verify.h" #include "hs_msg.h" #include "hs_kx.h" #include "session.h" static int32_t UpdateTicket(TLS_Ctx *ctx, NewSessionTicketMsg *msg, uint8_t *psk, uint32_t pskSize) { HITLS_Session *newSession = SESS_Copy(ctx->session); if (newSession == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16016, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy session info failed.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } SESS_SetStartTime(newSession, (uint64_t)BSL_SAL_CurrentSysTimeGet()); HITLS_SESS_SetTimeout(newSession, msg->ticketLifetimeHint); if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { SESS_SetTicketAgeAdd(newSession, msg->ticketAgeAdd); HITLS_SESS_SetMasterKey(newSession, psk, pskSize); } int32_t ret = SESS_SetTicket(newSession, msg->ticket, msg->ticketSize); if (ret != HITLS_SUCCESS) { HITLS_SESS_Free(newSession); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16017, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set ticket failed.", 0, 0, 0, 0); return ret; } HITLS_SESS_Free(ctx->session); ctx->session = newSession; /* The server may send multiple tickets. In this case, each ticket received will be notified to the user through * this callback, so that the client can obtain multiple sessions */ if (ctx->globalConfig != NULL && ctx->globalConfig->newSessionCb != NULL) { HITLS_SESS_UpRef(newSession); // It is convenient for users to take away and needs to be released by users if (ctx->globalConfig->newSessionCb(ctx, newSession) == 0) { /* If the user does not reference the session, the number of reference times decreases by 1 */ HITLS_SESS_Free(newSession); } } return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS_BASIC int32_t Tls12ClientRecvNewSeesionTicketProcess(TLS_Ctx *ctx, HS_Msg *hsMsg) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; /* The processing of the msg is complete when the NewSeesionTick operation is performed */ NewSessionTicketMsg *newSessionTicket = &hsMsg->body.newSessionTicket; if (newSessionTicket->ticketLifetimeHint != 0 && newSessionTicket->ticketSize != 0) { if (ctx->negotiatedInfo.isResume == true) { ret = UpdateTicket(ctx, newSessionTicket, NULL, 0); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } } else { /* Saved in the context */ hsCtx->ticketLifetimeHint = newSessionTicket->ticketLifetimeHint; hsCtx->ticketSize = newSessionTicket->ticketSize; hsCtx->ticket = newSessionTicket->ticket; newSessionTicket->ticket = NULL; newSessionTicket->ticketSize = 0; } } /* The server verify data needs to be calculated in advance */ ret = VERIFY_CalcVerifyData(ctx, false, hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15971, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client Calculate server finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13ClientRecvNewSessionTicketProcess(TLS_Ctx *ctx, HS_Msg *hsMsg) { if (!ctx->isClient) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); BSL_LOG_BINLOG_VARLEN(BINLOG_ID16018, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Unexpected msg: server recv new session ticket", HS_GetMsgTypeStr(hsMsg->type)); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } int32_t ret = HITLS_SUCCESS; NewSessionTicketMsg *msg = &hsMsg->body.newSessionTicket; /* If the value is 0, the ticket should be discarded immediately. After the TTO is backed up, the ctx->session field * is empty */ if (msg->ticketLifetimeHint == 0 || ctx->session == NULL) { return HS_ChangeState(ctx, TLS_CONNECTED); } uint8_t resumePsk[MAX_DIGEST_SIZE] = {0}; uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17081, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } ret = HS_TLS13DeriveResumePsk(ctx, msg->ticketNonce, msg->ticketNonceSize, resumePsk, hashLen); if (ret != HITLS_SUCCESS) { (void)memset_s(resumePsk, MAX_DIGEST_SIZE, 0, MAX_DIGEST_SIZE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16015, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Derive resume psk failed.", 0, 0, 0, 0); return ret; } ret = UpdateTicket(ctx, msg, resumePsk, hashLen); (void)memset_s(resumePsk, MAX_DIGEST_SIZE, 0, MAX_DIGEST_SIZE); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */
2301_79861745/bench_create
tls/handshake/recv/src/recv_new_session_ticket.c
C
unknown
6,402
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #include <stdint.h> #include <stdbool.h> #include "bsl_sal.h" #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "hitls_sni.h" #include "hitls_security.h" #include "tls.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "hs.h" #include "hs_ctx.h" #include "hs_verify.h" #include "hs_common.h" #include "hs_extensions.h" #include "hs_msg.h" #include "record.h" #include "transcript_hash.h" #include "session_mgr.h" #include "alpn.h" #include "alert.h" #include "hs_kx.h" #include "config_type.h" typedef int32_t (*CheckExtFunc)(TLS_Ctx *ctx, const ServerHelloMsg *serverHello); static int32_t ClientCheckPointFormats(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if ((!ctx->hsCtx->extFlag.havePointFormats) && serverHello->havePointFormats) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15255, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get point formats.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } /* The key exchange algorithm is not ECDHE */ if ((ctx->negotiatedInfo.cipherSuiteInfo.authAlg != HITLS_AUTH_ECDSA) && (ctx->negotiatedInfo.cipherSuiteInfo.kxAlg != HITLS_KEY_EXCH_ECDHE) && (ctx->negotiatedInfo.cipherSuiteInfo.kxAlg != HITLS_KEY_EXCH_ECDH) && (ctx->negotiatedInfo.cipherSuiteInfo.kxAlg != HITLS_KEY_EXCH_ECDHE_PSK)) { return HITLS_SUCCESS; } if (!serverHello->havePointFormats) { return HITLS_SUCCESS; } for (uint8_t i = 0u; i < serverHello->pointFormatsSize; i++) { /* The point format list contains uncompressed (0) */ if (serverHello->pointFormats[i] == 0u) { return HITLS_SUCCESS; } } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15256, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the point format extension in server hello is incorrect.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT); return HITLS_MSG_HANDLE_UNSUPPORT_POINT_FORMAT; } #ifdef HITLS_TLS_FEATURE_ALPN static int32_t ClientCheckNegotiatedAlpnOfServerHello(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { return ClientCheckNegotiatedAlpn( ctx, serverHello->haveSelectedAlpn, serverHello->alpnSelected, serverHello->alpnSelectedSize); } #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_FEATURE_SNI static int32_t ClientCheckServerName(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if ((ctx->hsCtx->extFlag.haveServerName == false) && (serverHello->haveServerName == true)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15263, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send server_name but get extended server_name .", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } /* Received null server_name extension for server hello message */ if ((ctx->hsCtx->extFlag.haveServerName == true) && (serverHello->haveServerName == true)) { /* Not in session resumption, and the client has previously sent the server_name extension */ if (ctx->session == NULL && ctx->config.tlsConfig.serverName != NULL && ctx->config.tlsConfig.serverNameSize > 0) { /* The server negotiates the extension of the server_name of the client successfully */ ctx->negotiatedInfo.isSniStateOK = true; ctx->hsCtx->serverNameSize = ctx->config.tlsConfig.serverNameSize; BSL_SAL_FREE(ctx->hsCtx->serverName); ctx->hsCtx->serverName = (uint8_t *)BSL_SAL_Dump(ctx->config.tlsConfig.serverName, ctx->hsCtx->serverNameSize * sizeof(uint8_t)); if (ctx->hsCtx->serverName == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17082, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SNI */ static int32_t ClientCheckExtendedMasterSecret(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if ((!ctx->hsCtx->extFlag.haveExtendedMasterSecret) && serverHello->haveExtendedMasterSecret) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15264, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get extended master secret.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } /* tls1.3 Ignore Extended Master Secret */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13 || ctx->negotiatedInfo.version < HITLS_VERSION_TLS12) { ctx->negotiatedInfo.isExtendedMasterSecret = false; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SESSION /* rfc 7627 5.3 Client and Server Behavior: Abbreviated Handshake If a client receives a ServerHello that accepts an abbreviated handshake, it behaves as follows: o If the original session did not use the "extended_master_secret" extension but the new ServerHello contains the extension, the client MUST abort the handshake. o If the original session used the extension but the new ServerHello does not contain the extension, the client MUST abort the handshake. */ if (ctx->negotiatedInfo.isResume && ctx->session != NULL) { uint8_t haveExtMasterSecret; HITLS_SESS_GetHaveExtMasterSecret(ctx->session, &haveExtMasterSecret); bool preEms = haveExtMasterSecret != 0; if (serverHello->haveExtendedMasterSecret != preEms) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17083, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ExtendedMasterSecret err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET; } } #endif /* HITLS_TLS_FEATURE_SESSION */ if (ctx->config.tlsConfig.isSupportExtendMasterSecret && !serverHello->haveExtendedMasterSecret) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17084, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ExtendedMasterSecret err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_INVALID_EXTENDED_MASTER_SECRET; } /* Configure the negotiation content to support the extended master secret */ ctx->negotiatedInfo.isExtendedMasterSecret = (ctx->hsCtx->extFlag.haveExtendedMasterSecret && serverHello->haveExtendedMasterSecret); return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 static int32_t ClientCheckKeyShare(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if ((!ctx->hsCtx->extFlag.haveKeyShare) && serverHello->haveKeyShare) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15265, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get key share.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } return HITLS_SUCCESS; } static int32_t ClientCheckPreShareKey(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if ((!ctx->hsCtx->extFlag.havePreShareKey) && serverHello->haveSelectedIdentity) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15266, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get pre share key.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } return HITLS_SUCCESS; } static int32_t ClientCheckSupportedVersions(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if ((!ctx->hsCtx->extFlag.haveSupportedVers) && serverHello->haveSupportedVersion) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16133, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get supported versions.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t ClientCheckRenegoInfoDuringFirstHandshake(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { /* If the peer does not support the renegotiation, return */ if (!serverHello->haveSecRenego) { /* Renegotiate info is not checked in tls13 protocol. */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { return HITLS_SUCCESS; } if (!ctx->config.tlsConfig.allowLegacyRenegotiate) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15899, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Legacy Renegotiate is not allowed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } return HITLS_SUCCESS; } /* For the first handshake, if the security renegotiation information is not empty, a failure message is returned. */ if (serverHello->secRenegoInfoSize != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15958, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "secRenegoInfoSize should be 0 in client initial handhsake.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } /* Configure the security renegotiation function */ ctx->negotiatedInfo.isSecureRenegotiation = true; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION static int32_t ClientCheckRenegoInfoDuringRenegotiation(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { /* Verify the security renegotiation information */ const uint8_t *clientData = ctx->negotiatedInfo.clientVerifyData; uint32_t clientDataSize = ctx->negotiatedInfo.clientVerifyDataSize; const uint8_t *serverData = ctx->negotiatedInfo.serverVerifyData; uint32_t serverDataSize = ctx->negotiatedInfo.serverVerifyDataSize; if (clientData == NULL || serverData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17085, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "intput null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } if (serverHello->secRenegoInfoSize != (clientDataSize + serverDataSize)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15900, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "secRenegoInfoSize(%u) error, expect %u.", serverHello->secRenegoInfoSize, (clientDataSize + serverDataSize), 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } if (memcmp(serverHello->secRenegoInfo, clientData, clientDataSize) != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15901, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "check client secRenegoInfo verify data failed during renegotiation.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } if (memcmp(&serverHello->secRenegoInfo[clientDataSize], serverData, serverDataSize) != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15902, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "check server secRenegoInfo verify data failed during renegotiation.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_RENEGOTIATION_FAIL); return HITLS_MSG_HANDLE_RENEGOTIATION_FAIL; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ static int32_t ClientCheckAndProcessRenegoInfo(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { /* Not in the renegotiation state */ if (!ctx->negotiatedInfo.isRenegotiation) { return ClientCheckRenegoInfoDuringFirstHandshake(ctx, serverHello); } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION /* Renegotiation state */ return ClientCheckRenegoInfoDuringRenegotiation(ctx, serverHello); #else return HITLS_SUCCESS; #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ } #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET static int32_t ClientCheckTicketExternsion(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if ((!ctx->hsCtx->extFlag.haveTicket) && serverHello->haveTicket) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15972, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get ticket externsion.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13 && serverHello->haveTicket) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15912, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TLS1.3 client get server hello ticket externsion.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } /* Set whether to support ticket extension */ ctx->negotiatedInfo.isTicket = serverHello->haveTicket; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_ETM static int32_t ClientCheckEncryptThenMac(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if (!ctx->hsCtx->extFlag.haveEncryptThenMac && serverHello->haveEncryptThenMac) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15920, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client did not send but get encrypt then mac.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } /* The user does not support the EncryptThenMac extension, but receives the EncryptThenMac extension from the server */ if (!ctx->config.tlsConfig.isEncryptThenMac && serverHello->haveEncryptThenMac) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15931, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client do not support encrypt then mac.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNSUPPORTED_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } /* During renegotiation, EncryptThenMac cannot be converted to MacThenEncrypt */ if (ctx->negotiatedInfo.isRenegotiation && ctx->negotiatedInfo.isEncryptThenMac && !serverHello->haveEncryptThenMac) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15934, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "regotiation should not change encrypt then mac to mac then encrypt.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ENCRYPT_THEN_MAC_ERR); return HITLS_MSG_HANDLE_ENCRYPT_THEN_MAC_ERR; } /* This extension does not need to be negotiated for tls1.3 */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { return HITLS_SUCCESS; } /* Set the negotiated EncryptThenMac */ if (serverHello->haveEncryptThenMac) { ctx->negotiatedInfo.isEncryptThenMac = true; } else { ctx->negotiatedInfo.isEncryptThenMac = false; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_ETM */ static int32_t ClientCheckExtensionsFlag(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { static const CheckExtFunc extInfoList[] = { ClientCheckPointFormats, #ifdef HITLS_TLS_FEATURE_SNI ClientCheckServerName, #endif /* HITLS_TLS_FEATURE_SNI */ ClientCheckExtendedMasterSecret, #ifdef HITLS_TLS_FEATURE_ALPN ClientCheckNegotiatedAlpnOfServerHello, #endif /* HITLS_TLS_FEATURE_ALPN */ #ifdef HITLS_TLS_PROTO_TLS13 ClientCheckKeyShare, ClientCheckPreShareKey, ClientCheckSupportedVersions, #endif /* HITLS_TLS_PROTO_TLS13 */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) ClientCheckAndProcessRenegoInfo, #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET ClientCheckTicketExternsion, #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_FEATURE_ETM ClientCheckEncryptThenMac, #endif /* HITLS_TLS_FEATURE_ETM */ }; int32_t ret; for (uint32_t i = 0; i < sizeof(extInfoList) / sizeof(extInfoList[0]); i++) { ret = extInfoList[i](ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } static bool IsCipherSuiteSupport(const TLS_Ctx *ctx, uint16_t cipherSuite) { if (!IsCipherSuiteAllowed(ctx, cipherSuite)) { return false; } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { for (uint32_t index = 0; index < ctx->config.tlsConfig.tls13cipherSuitesSize; index++) { if (cipherSuite == ctx->config.tlsConfig.tls13CipherSuites[index]) { return true; } } } #endif /* HITLS_TLS_PROTO_TLS13 */ for (uint32_t index = 0; index < ctx->config.tlsConfig.cipherSuitesSize; index++) { if (cipherSuite == ctx->config.tlsConfig.cipherSuites[index]) { return true; } } return false; } static int32_t ClientCheckCipherSuite(TLS_Ctx *ctx, const ServerHelloMsg *serverHello, bool isHrr) { int32_t ret = HITLS_SUCCESS; (void)isHrr; if (!IsCipherSuiteSupport(ctx, serverHello->cipherSuite)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15269, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "no supported cipher suites found.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); return HITLS_MSG_HANDLE_CIPHER_SUITE_ERR; } #ifdef HITLS_TLS_PROTO_TLS13 /* In TLS1.3, if the hello retry request message is received, ensure that the cipherSuite of the server hello * message is the same as the cipherSuite */ if (!isHrr && ctx->hsCtx->haveHrr) { if (serverHello->cipherSuite != ctx->negotiatedInfo.cipherSuiteInfo.cipherSuite) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15270, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cipherSuite in server hello (0x%02x) is defferent from hello retry request (0x%02x).", serverHello->cipherSuite, ctx->negotiatedInfo.cipherSuiteInfo.cipherSuite, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE); return HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ ret = CFG_GetCipherSuiteInfo(serverHello->cipherSuite, &ctx->negotiatedInfo.cipherSuiteInfo); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15271, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get cipher suite information fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #ifdef HITLS_TLS_FEATURE_SECURITY /* Check the security of the cipher suite */ ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_CIPHER_SHARED, 0, 0, (void *)&ctx->negotiatedInfo.cipherSuiteInfo); if (ret != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17087, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SslCheck fail, ret %d", ret, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INSUFFICIENT_SECURITY); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSECURE_CIPHER_SUITE); return HITLS_MSG_HANDLE_UNSECURE_CIPHER_SUITE; } #endif /* HITLS_TLS_FEATURE_SECURITY */ /* Sets the key negotiation algorithm. */ ctx->hsCtx->kxCtx->keyExchAlgo = ctx->negotiatedInfo.cipherSuiteInfo.kxAlg; BSL_LOG_BINLOG_VARLEN(BINLOG_ID15272, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "ClientCheckCipherSuite: negotiated ciphersuite is [%s].", ctx->negotiatedInfo.cipherSuiteInfo.name); return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t ClientCheckVersion(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { uint16_t clientMinVersion = ctx->config.tlsConfig.minVersion; uint16_t clientMaxVersion = ctx->config.tlsConfig.maxVersion; uint16_t serverVersion = serverHello->version; if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { if ((serverVersion > clientMinVersion) || (serverVersion < clientMaxVersion)) { /* The DTLS version selected by the server is too early and the negotiation cannot be continued */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15267, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client support version is from %02x to %02x, server selected unsupported version %02x.", clientMinVersion, clientMaxVersion, serverVersion, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } } else { if ((serverVersion < clientMinVersion) || (serverVersion > clientMaxVersion)) { /* The TLS version selected by the server is too early and cannot be negotiated */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15268, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client support version is from %02x to %02x, server selected unsupported version %02x.", clientMinVersion, clientMaxVersion, serverVersion, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } } #ifdef HITLS_TLS_FEATURE_SECURITY int32_t ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_VERSION, 0, serverHello->version, NULL); if (ret != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17088, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SslCheck fail, ret %d", ret, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INSUFFICIENT_SECURITY); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSECURE_VERSION); return HITLS_MSG_HANDLE_UNSECURE_VERSION; } #endif /* HITLS_TLS_FEATURE_SECURITY */ ctx->negotiatedInfo.version = serverVersion; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SESSION static int32_t ClientCheckResumeServerHello(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { uint16_t version = 0; uint16_t cipherSuite = 0; uint8_t haveExtMasterSecret = 0; HITLS_SESS_GetProtocolVersion(ctx->session, &version); HITLS_SESS_GetCipherSuite(ctx->session, &cipherSuite); HITLS_SESS_GetHaveExtMasterSecret(ctx->session, &haveExtMasterSecret); /* Check the version information */ if (serverHello->version != version) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15273, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the version of resume server hello is different from the pre connect.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_VERSION); return HITLS_MSG_HANDLE_ILLEGAL_VERSION; } /* Check the cipher suite information */ if (serverHello->cipherSuite != cipherSuite) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15274, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the cipher suite of resume server hello is different from the pre connect.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE); return HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE; } /* Check the extended master secret information */ if (serverHello->haveExtendedMasterSecret != (bool)haveExtMasterSecret) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15275, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "session resume error:can not downgrade from extended master secret.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_EXTRENED_MASTER_SECRET); return HITLS_MSG_HANDLE_ILLEGAL_EXTRENED_MASTER_SECRET; } return HITLS_SUCCESS; } static bool SessionIdCmp(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; if ((hsCtx->sessionIdSize == 0u) || (serverHello->sessionIdSize == 0u)) { return false; } if (hsCtx->sessionIdSize != serverHello->sessionIdSize) { return false; } if (memcmp(hsCtx->sessionId, serverHello->sessionId, hsCtx->sessionIdSize) != 0) { return false; } return true; } static int32_t ClientCopySessionId(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; BSL_SAL_FREE(hsCtx->sessionId); hsCtx->sessionId = (uint8_t *)BSL_SAL_Calloc(1u, HITLS_SESSION_ID_MAX_SIZE); if (hsCtx->sessionId == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15276, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "session Id malloc fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } ret = memcpy_s(hsCtx->sessionId, HITLS_SESSION_ID_MAX_SIZE, serverHello->sessionId, serverHello->sessionIdSize); if (ret != EOK) { BSL_SAL_FREE(hsCtx->sessionId); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15277, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "session Id memcpy fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } hsCtx->sessionIdSize = serverHello->sessionIdSize; return HITLS_SUCCESS; } static int32_t ClientCheckIfResumeFromSession(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { bool isResume = false; ctx->negotiatedInfo.isResume = false; if (ctx->session == NULL || serverHello->sessionIdSize == 0u) { return HITLS_SUCCESS; } isResume = SessionIdCmp(ctx, serverHello); if (isResume == true) { /* Resume the session */ ctx->negotiatedInfo.isResume = true; /* Check whether the version number, cipher suite, and master key extension match */ return ClientCheckResumeServerHello(ctx, serverHello); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION */ static int32_t ClientCheckServerHello(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { int32_t ret = ClientCheckVersion(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } ret = memcpy_s(ctx->hsCtx->serverRandom, HS_RANDOM_SIZE, serverHello->randomValue, HS_RANDOM_SIZE); if (ret != EOK) { return ret; } #ifdef HITLS_TLS_FEATURE_SESSION /* Check the session resumption. Check whether the session ID, version number, cipher suite, and master key * extension match */ ret = ClientCheckIfResumeFromSession(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } /* Save the session ID for complete handshake */ if (ctx->negotiatedInfo.isResume == false && serverHello->sessionIdSize > 0) { ret = ClientCopySessionId(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_SESSION */ ret = ClientCheckCipherSuite(ctx, serverHello, false); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_CheckReceivedExtension(ctx, SERVER_HELLO, serverHello->extensionTypeMask, HS_EX_TYPE_TLS1_2_ALLOWED_OF_SERVER_HELLO); if (ret != HITLS_SUCCESS) { return ret; } return ClientCheckExtensionsFlag(ctx, serverHello); } // The client processes the Server Hello message int32_t ClientRecvServerHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = HITLS_SUCCESS; const ServerHelloMsg *serverHello = &msg->body.serverHello; ret = ClientCheckServerHello(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } ret = VERIFY_SetHash(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), ctx->hsCtx->verifyCtx, ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17089, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VERIFY_SetHash fail", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_FEATURE_SESSION if (ctx->negotiatedInfo.isResume == true) { ret = HS_ResumeKeyEstablish(ctx); if (ret != HITLS_SUCCESS) { return ret; } if (ctx->negotiatedInfo.isTicket) { return HS_ChangeState(ctx, TRY_RECV_NEW_SESSION_TICKET); } /* Calculate the 'server verify data' for verifying the 'finished' message of the server. */ ret = VERIFY_CalcVerifyData(ctx, false, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15278, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client Calculate server finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_FEATURE_SESSION */ /* If the server rejects the session resume request, the system clears the ccs that may be received in disorder */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); /* Update the state machine. */ /* If the PSK, DHE_PSK, ECDHE_PSK, or ANON_DH key negotiation is used, skip TRY_RECV_CERTIFICATIONATE */ #ifdef HITLS_TLS_FEATURE_PSK if (!IsNeedCertPrepare(&ctx->negotiatedInfo.cipherSuiteInfo)) { return HS_ChangeState(ctx, TRY_RECV_SERVER_KEY_EXCHANGE); } #endif /* HITLS_TLS_FEATURE_PSK */ return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13ClientCheckHelloRetryRequest(TLS_Ctx *ctx, const ServerHelloMsg *helloRetryRequest) { /* If the second Hello Retry Request message is received over the same link, an alert message needs to be sent */ if (ctx->hsCtx->haveHrr) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15279, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "duplicate hello retry request.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_DUPLICATE_HELLO_RETYR_REQUEST); return HITLS_MSG_HANDLE_DUPLICATE_HELLO_RETYR_REQUEST; } ctx->hsCtx->haveHrr = true; /* Update state: The hello retry request has been received */ /* The supportedVersion is a mandatory extension */ if (helloRetryRequest->haveSupportedVersion == false) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15280, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "missing supported version extension in server hello or hello retry request.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_MISSING_EXTENSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_MISSING_EXTENSION); return HITLS_MSG_HANDLE_MISSING_EXTENSION; } /* If the hello retry request does not modify the client hello, an alert message is sent */ if ((helloRetryRequest->haveCookie == false) && (helloRetryRequest->haveKeyShare == false)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15281, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the hello retry reques would not result in any change in the client hello.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_MISSING_EXTENSION); return HITLS_MSG_HANDLE_MISSING_EXTENSION; } return HITLS_SUCCESS; } static int32_t Tls13ClientCheckSessionId(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { /* The legacy_session_id_echo field must be the same as the sent field */ if (ctx->hsCtx->sessionIdSize != serverHello->sessionIdSize) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17090, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sessionIdSize err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID; } if (serverHello->sessionIdSize != 0) { if (memcmp(ctx->hsCtx->sessionId, serverHello->sessionId, serverHello->sessionIdSize) != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17091, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sessionId err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID; } } return HITLS_SUCCESS; } static int32_t Tls13ClientCheckServerHello(TLS_Ctx *ctx, const ServerHelloMsg *serverHello, bool isHrr) { int32_t ret = HITLS_SUCCESS; ctx->negotiatedInfo.version = serverHello->supportedVersion; ret = memcpy_s(ctx->hsCtx->serverRandom, HS_RANDOM_SIZE, serverHello->randomValue, HS_RANDOM_SIZE); if (ret != EOK) { return ret; } ret = Tls13ClientCheckSessionId(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } return ClientCheckCipherSuite(ctx, serverHello, isHrr); } static int32_t ClientCheckHrrKeyShareExtension(TLS_Ctx *ctx, const ServerHelloMsg *helloRetryRequest) { if (helloRetryRequest->haveKeyShare == false) { return HITLS_SUCCESS; } /* The keyshare extension of hrr contains only group and does not contain other fields */ if (helloRetryRequest->keyShare.keyExchangeSize != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15282, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the keyshare keyExchangeSize is not 0 in hrr keyshare.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } uint16_t selectedGroup = helloRetryRequest->keyShare.group; const uint16_t *groups = ctx->config.tlsConfig.groups; uint32_t numOfGroups = ctx->config.tlsConfig.groupsSize; /* The selected group exist in the key share extension of the original client hello and no cookie exchange requested */ if (ctx->negotiatedInfo.cookie == NULL && (selectedGroup == ctx->hsCtx->kxCtx->keyExchParam.share.group || selectedGroup == ctx->hsCtx->kxCtx->keyExchParam.share.secondGroup)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15283, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the selected group extension is corresponded to a group in client hello key share.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } /* The selected group must exist in the supported groups extension of the original client hello */ bool found = false; for (uint32_t i = 0; i < numOfGroups; i++) { if (selectedGroup == groups[i]) { found = true; break; } } if (found == false) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15284, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the selected group extension could not correspond to a group in client hello supported groups.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } if (selectedGroup == ctx->hsCtx->kxCtx->keyExchParam.share.secondGroup) { SAL_CRYPT_FreeEcdhKey(ctx->hsCtx->kxCtx->key); ctx->hsCtx->kxCtx->key = ctx->hsCtx->kxCtx->secondKey; ctx->hsCtx->kxCtx->secondKey = NULL; ctx->hsCtx->kxCtx->keyExchParam.share.group = selectedGroup; ctx->hsCtx->kxCtx->keyExchParam.share.secondGroup = HITLS_NAMED_GROUP_BUTT; } // Save the selected group ctx->negotiatedInfo.negotiatedGroup = selectedGroup; return HITLS_SUCCESS; } /* If an implementation receives an extension * which it recognizes and which is not specified for the message in * which it appears, it MUST abort the handshake with an * "illegal_parameter" alert. */ static int32_t ClientCheckHrrExtraExtension(TLS_Ctx *ctx, const ServerHelloMsg *helloRetryRequest) { if (helloRetryRequest->haveServerName || helloRetryRequest->haveExtendedMasterSecret || helloRetryRequest->havePointFormats || helloRetryRequest->haveSelectedAlpn || helloRetryRequest->haveSelectedIdentity || helloRetryRequest->haveSecRenego || helloRetryRequest->haveTicket || helloRetryRequest->haveEncryptThenMac) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17092, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "these extensions are not specified in the hrr message", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); return HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE; } return HITLS_SUCCESS; } static int32_t ClientCheckHrrCookieExtension(TLS_Ctx *ctx, const ServerHelloMsg *helloRetryRequest) { if (helloRetryRequest->haveCookie == false) { return HITLS_SUCCESS; } BSL_SAL_FREE(ctx->negotiatedInfo.cookie); // Clearing Old Memory ctx->negotiatedInfo.cookie = BSL_SAL_Dump(helloRetryRequest->cookie, helloRetryRequest->cookieLen); if (ctx->negotiatedInfo.cookie == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15285, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cookie malloc fail when process hello retry request.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } ctx->negotiatedInfo.cookieSize = helloRetryRequest->cookieLen; return HITLS_SUCCESS; } static int32_t Tls13ClientCheckHrrExtension(TLS_Ctx *ctx, const ServerHelloMsg *helloRetryRequest) { int32_t ret = HITLS_SUCCESS; ret = HS_CheckReceivedExtension(ctx, HELLO_RETRY_REQUEST, helloRetryRequest->extensionTypeMask, HS_EX_TYPE_TLS1_3_ALLOWED_OF_HELLO_RETRY_REQUEST); if (ret != HITLS_SUCCESS) { return ret; } /* Check whether there are redundant extensions */ ret = ClientCheckHrrExtraExtension(ctx, helloRetryRequest); if (ret != HITLS_SUCCESS) { return ret; } /* Check the key share extension */ ret = ClientCheckHrrCookieExtension(ctx, helloRetryRequest); if (ret != HITLS_SUCCESS) { return ret; } /* Check the cookie extension */ return ClientCheckHrrKeyShareExtension(ctx, helloRetryRequest); } int32_t Tls13ClientRecvHelloRetryRequestProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = HITLS_SUCCESS; const ServerHelloMsg *helloRetryRequest = &msg->body.serverHello; ret = Tls13ClientCheckHelloRetryRequest(ctx, helloRetryRequest); if (ret != HITLS_SUCCESS) { return ret; } /* Check whether the format of the Hello Retry Request message is the same as that of the Server Hello message * except the extended fields */ ret = Tls13ClientCheckServerHello(ctx, helloRetryRequest, true); if (ret != HITLS_SUCCESS) { return ret; } ret = Tls13ClientCheckHrrExtension(ctx, helloRetryRequest); if (ret != HITLS_SUCCESS) { return ret; } /* According to RFC 8446 4.4.1, If the Hello Retry Request message is sent, special Transcript-Hash data needs to be * constructed */ ret = VERIFY_HelloRetryRequestVerifyProcess(ctx); if (ret != HITLS_SUCCESS) { return ret; } return HS_ChangeState(ctx, TRY_SEND_CLIENT_HELLO); } #ifdef HITLS_TLS_PROTO_TLS_BASIC static int32_t CheckDowngradeRandom(TLS_Ctx *ctx, const ServerHelloMsg *serverHello, uint16_t *negotiatedVersion) { const uint8_t *downgradeArr = NULL; uint32_t downgradeArrLen = 0; if (serverHello->version == HITLS_VERSION_TLS12) { /* The server that attempts to negotiate TLS1.2 should not send the server hello with the random */ downgradeArr = HS_GetTls12DowngradeRandom(&downgradeArrLen); if (memcmp(&serverHello->randomValue[HS_RANDOM_SIZE - downgradeArrLen], downgradeArr, downgradeArrLen) != 0) { *negotiatedVersion = HITLS_VERSION_TLS12; return HITLS_SUCCESS; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15286, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "tls1.2 server hello with downgrade random value.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ static int32_t GetNegotiatedVersion(TLS_Ctx *ctx, const ServerHelloMsg *serverHello, uint16_t *negotiatedVersion) { /* As a client that supports TLS1.3, if the received server hello message does not contain the supported version * extension, the peer end wants to negotiate a version earlier than TLS1.3 */ if (!serverHello->haveSupportedVersion) { if (serverHello->version < HITLS_VERSION_TLS12) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16169, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client cannot negotiate a version.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } return CheckDowngradeRandom(ctx, serverHello, negotiatedVersion); } /* If the serverHello of TLS1.3 is used, the version selected by the server must be earlier than TLS1.3, and the * legacy_version field must be TLS1.2 */ if (serverHello->version != HITLS_VERSION_TLS12) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15288, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server version error, legacy version is 0x%02x.", serverHello->version, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } /* If the "supported_versions" extension in the ServerHello contains a version not offered by the client or * contains a version prior to TLS 1.3, the client MUST abort the handshake with an "illegal_parameter" alert. */ if (serverHello->supportedVersion != HITLS_VERSION_TLS13) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17307, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server version error, selected version is 0x%02x.", serverHello->supportedVersion, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } *negotiatedVersion = HITLS_VERSION_TLS13; return HITLS_SUCCESS; } static int32_t ClientProcessKeyShare(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if (serverHello->haveKeyShare == false) { return HITLS_SUCCESS; } uint32_t keyshareLen = 0u; /* The keyshare extension of the server must contain the keyExchange field */ if (serverHello->keyShare.keyExchangeSize == 0 || serverHello->keyShare.group == HITLS_NAMED_GROUP_BUTT || /* Check whether the sent support group is the same as the negotiated group */ (serverHello->keyShare.group != ctx->hsCtx->kxCtx->keyExchParam.share.group && serverHello->keyShare.group != ctx->hsCtx->kxCtx->keyExchParam.share.secondGroup)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15289, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "the keyshare parameter is illegal.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } const KeyShare *keyShare = &serverHello->keyShare; if (keyShare->group == ctx->hsCtx->kxCtx->keyExchParam.share.secondGroup) { SAL_CRYPT_FreeEcdhKey(ctx->hsCtx->kxCtx->key); ctx->hsCtx->kxCtx->key = ctx->hsCtx->kxCtx->secondKey; ctx->hsCtx->kxCtx->secondKey = NULL; ctx->hsCtx->kxCtx->keyExchParam.share.group = keyShare->group; ctx->hsCtx->kxCtx->keyExchParam.share.secondGroup = HITLS_NAMED_GROUP_BUTT; } const TLS_GroupInfo *groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, keyShare->group); if (groupInfo == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16247, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "group info not found", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } if (groupInfo->isKem) { keyshareLen = groupInfo->ciphertextLen; } else { keyshareLen = groupInfo->pubkeyLen; } if (keyshareLen == 0u || keyshareLen != keyShare->keyExchangeSize) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17326, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid keyShare length [%d]", keyShare->keyExchangeSize, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } uint8_t *peerPubkey = BSL_SAL_Dump(keyShare->keyExchange, keyshareLen); if (peerPubkey == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15290, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc peerPubkey fail when process server hello key share.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } BSL_SAL_FREE(ctx->hsCtx->kxCtx->peerPubkey); ctx->hsCtx->kxCtx->peerPubkey = peerPubkey; ctx->hsCtx->kxCtx->pubKeyLen = keyshareLen; ctx->negotiatedInfo.negotiatedGroup = serverHello->keyShare.group; return HITLS_SUCCESS; } static int32_t ClientProcessPreSharedKey(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { if (serverHello->haveSelectedIdentity == false) { return HITLS_SUCCESS; } PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; HITLS_Session *pskSession = NULL; bool isResumePsk = false; BSL_SAL_FREE(pskInfo->psk); if (pskInfo->resumeSession != NULL && serverHello->selectedIdentity == 0) { pskSession = pskInfo->resumeSession; isResumePsk = true; } else if (pskInfo->userPskSess == NULL || serverHello->selectedIdentity != pskInfo->userPskSess->num) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ILLEGAL_PSK_IDENTITY); return HITLS_MSG_HANDLE_ILLEGAL_PSK_IDENTITY; } else { pskSession = pskInfo->userPskSess->pskSession; } pskInfo->selectIndex = serverHello->selectedIdentity; uint8_t psk[HS_PSK_MAX_LEN] = {0}; uint32_t pskLen = HS_PSK_MAX_LEN; uint16_t cipherSuite = 0; HITLS_SESS_GetCipherSuite(pskSession, &cipherSuite); CipherSuiteInfo cipherInfo = {0}; int32_t ret = CFG_GetCipherSuiteInfo(cipherSuite, &cipherInfo); if (ret != HITLS_SUCCESS) { return RETURN_ALERT_PROCESS(ctx, ret, BINLOG_ID17093, "GetCipherSuiteInfo fail", ALERT_INTERNAL_ERROR); } /* The hash algorithm used by the PSK must match the negotiated cipher suite */ if (cipherInfo.hashAlg != ctx->negotiatedInfo.cipherSuiteInfo.hashAlg) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_PSK_SESSION_INVALID_CIPHER_SUITE); return HITLS_MSG_HANDLE_PSK_SESSION_INVALID_CIPHER_SUITE; } /* The session is available and the PSK is obtained */ ret = HITLS_SESS_GetMasterKey(pskSession, psk, &pskLen); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); return ret; } pskInfo->psk = BSL_SAL_Dump(psk, pskLen); BSL_SAL_CleanseData(psk, HS_PSK_MAX_LEN); if (pskInfo->psk == NULL) { (void)memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return RETURN_ALERT_PROCESS(ctx, HITLS_MEMALLOC_FAIL, BINLOG_ID17094, "dump psk fail", ALERT_INTERNAL_ERROR); } pskInfo->pskLen = pskLen; ctx->negotiatedInfo.isResume = isResumePsk; return HITLS_SUCCESS; } static uint32_t GetServertls13AuthType(const ServerHelloMsg *serverHello) { uint32_t tls13BasicKeyExMode = 0; if (serverHello->haveKeyShare && serverHello->haveSelectedIdentity) { tls13BasicKeyExMode = TLS13_KE_MODE_PSK_WITH_DHE; } else if (serverHello->haveSelectedIdentity) { tls13BasicKeyExMode = TLS13_KE_MODE_PSK_ONLY; } else if (serverHello->haveKeyShare) { tls13BasicKeyExMode = TLS13_CERT_AUTH_WITH_DHE; } return tls13BasicKeyExMode; } static int32_t Tls13ProcessServerHelloExtension(TLS_Ctx *ctx, const ServerHelloMsg *serverHello) { int32_t ret = 0; ret = HS_CheckReceivedExtension(ctx, SERVER_HELLO, serverHello->extensionTypeMask, HS_EX_TYPE_TLS1_3_ALLOWED_OF_SERVER_HELLO); if (ret != HITLS_SUCCESS) { return ret; } /* Check whether the extension that is not sent is received */ ret = ClientCheckExtensionsFlag(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } uint32_t tls13BasicKeyExMode = GetServertls13AuthType(serverHello) & ctx->negotiatedInfo.tls13BasicKeyExMode; if (tls13BasicKeyExMode == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16141, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server selects the mode in which the client does not send.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_HANDSHAKE_FAILURE); return HITLS_MSG_HANDLE_HANDSHAKE_FAILURE; } ctx->negotiatedInfo.tls13BasicKeyExMode = tls13BasicKeyExMode; ret = ClientProcessKeyShare(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } return ClientProcessPreSharedKey(ctx, serverHello); } int32_t Tls13ProcessServerHello(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = HITLS_SUCCESS; const ServerHelloMsg *serverHello = &msg->body.serverHello; /* Check all fields except the extended fields in the server hello message */ ret = Tls13ClientCheckServerHello(ctx, serverHello, false); if (ret != HITLS_SUCCESS) { return ret; } ret = Tls13ProcessServerHelloExtension(ctx, serverHello); if (ret != HITLS_SUCCESS) { return ret; } ret = VERIFY_SetHash(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), ctx->hsCtx->verifyCtx, ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (ret != HITLS_SUCCESS) { return ret; } /* Client key derivation */ ret = HS_TLS13CalcServerHelloProcessSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17095, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcServerHelloProcessSecret fail", 0, 0, 0, 0); return ret; } ret = HS_TLS13DeriveHandshakeTrafficSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17096, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveHandshakeTrafficSecret fail", 0, 0, 0, 0); return ret; } /* The message after ServerHello is encrypted by ServerTrafficSecret and needs to be activated for decryption */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17097, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } ret = HS_SwitchTrafficKey(ctx, ctx->hsCtx->serverHsTrafficSecret, hashLen, false); if (ret != HITLS_SUCCESS) { return ret; } return HS_ChangeState(ctx, TRY_RECV_ENCRYPTED_EXTENSIONS); } int32_t Tls13ClientRecvServerHelloProcess(TLS_Ctx *ctx, const HS_Msg *msg) { int32_t ret = HITLS_SUCCESS; const ServerHelloMsg *serverHello = &msg->body.serverHello; /* Obtain the intention of the server and determine the version to be negotiated by the server */ uint16_t negotiatedVersion = 0; ret = GetNegotiatedVersion(ctx, serverHello, &negotiatedVersion); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_PROTO_TLS_BASIC if (negotiatedVersion < HITLS_VERSION_TLS13) { /* The keyshare is prepared when the TLS1.3 clientHello message is sent, so the old memory needs to be freed * here first */ HS_KeyExchCtxFree(ctx->hsCtx->kxCtx); ctx->hsCtx->kxCtx = HS_KeyExchCtxNew(); if (ctx->hsCtx->kxCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17098, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "KeyExchCtxNew fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } return ClientRecvServerHelloProcess(ctx, msg); } #endif /* only for tls13 */ uint32_t hrrRandomSize = 0; const uint8_t *hrrRandom = HS_GetHrrRandom(&hrrRandomSize); /* Check the random number. If the message is a hello retry request message, update the client hello message */ if (memcmp(serverHello->randomValue, hrrRandom, hrrRandomSize) == 0) { return Tls13ClientRecvHelloRetryRequestProcess(ctx, msg); } return Tls13ProcessServerHello(ctx, msg); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/recv/src/recv_server_hello.c
C
unknown
56,990
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "recv_process.h" #ifdef HITLS_TLS_HOST_CLIENT #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include "rec.h" #include "hs_ctx.h" #include "hs_common.h" int32_t ClientRecvServerHelloDoneProcess(TLS_Ctx *ctx) { /** get client infomation */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) /* clear the retransmission queue */ REC_RetransmitListClean(ctx->recCtx); #endif /** Certificate messages are sent whenever a server certificate request is received, regardless of whether the client has a proper certificate. */ if (hsCtx->isNeedClientCert) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE); } return HS_ChangeState(ctx, TRY_SEND_CLIENT_KEY_EXCHANGE); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/recv/src/recv_server_hello_done.c
C
unknown
1,469
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include <stdint.h> #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_msg.h" #include "hs_kx.h" int32_t ClientRecvServerKxProcess(TLS_Ctx *ctx, HS_Msg *msg) { int32_t ret; /** get the client infomation */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; ServerKeyExchangeMsg *serverKxMsg = &msg->body.serverKeyExchange; (void)serverKxMsg; #ifdef HITLS_TLS_FEATURE_PSK if (IsPskNegotiation(ctx)) { ret = HS_ProcessServerKxMsgIdentityHint(ctx, serverKxMsg); if (ret != HITLS_SUCCESS) { // log here return ret; } } #endif /* HITLS_TLS_FEATURE_PSK */ /* process key exchange message from the server */ switch (hsCtx->kxCtx->keyExchAlgo) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: // include TLCP case HITLS_KEY_EXCH_ECDHE_PSK: ret = HS_ProcessServerKxMsgEcdhe(ctx, serverKxMsg); break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = HS_ProcessServerKxMsgDhe(ctx, serverKxMsg); break; #endif /* HITLS_TLS_SUITE_KX_DHE */ case HITLS_KEY_EXCH_PSK: case HITLS_KEY_EXCH_RSA_PSK: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: // signature is verified at parse time #endif ret = HITLS_SUCCESS; break; default: ret = HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG; ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); break; } if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15857, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client process server key exchange msg fail.", 0, 0, 0, 0); return ret; } /* update the state machine */ return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE_REQUEST); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/recv/src/recv_server_key_exchange.c
C
unknown
2,823
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HS_STATE_SEND_H #define HS_STATE_SEND_H #include <stdint.h> #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Handshake layer state machine message sending processing * * @param ctx [IN] TLS object * * @retval HITLS_SUCCESS * @retval HITLS_MSG_HANDLE_UNSUPPORT_VERSION The TLS version is not supported * @retval For details, see hitls_error.h */ int32_t HS_SendMsgProcess(TLS_Ctx *ctx); /** * @brief Key update message sending and processing * * @param ctx [IN] TLS object * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t HS_HandleSendKeyUpdate(TLS_Ctx *ctx); #ifdef __cplusplus } #endif /* end __cplusplus */ #endif /* end HS_STATE_SEND_H */
2301_79861745/bench_create
tls/handshake/send/include/hs_state_send.h
C
unknown
1,275
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs.h" #include "hs_common.h" #include "send_process.h" #include "hs_kx.h" #include "pack.h" #include "bsl_uio.h" #include "bsl_sal.h" #ifdef HITLS_TLS_FEATURE_KEY_UPDATE static int32_t Tls13SendKeyUpdateProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; if (hsCtx->msgLen == 0) { ret = HS_PackMsg(ctx, KEY_UPDATE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15791, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack tls1.3 key update msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15792, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 key update msg success.", 0, 0, 0, 0); /* After the key update message is sent, the local application traffic key is updated and activated. */ ret = HS_TLS13UpdateTrafficSecret(ctx, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15793, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "tls1.3 out key update fail", 0, 0, 0, 0); return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15794, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "tls1.3 send key update success.", 0, 0, 0, 0); ctx->isKeyUpdateRequest = false; ctx->keyUpdateType = HITLS_KEY_UPDATE_REQ_END; return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_FEATURE_KEY_UPDATE */ #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) static int32_t SendFinishedProcess(TLS_Ctx *ctx) { #ifdef HITLS_TLS_HOST_CLIENT if (ctx->isClient) { #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsClientSendFinishedProcess(ctx); } #endif #ifdef HITLS_TLS_PROTO_TLS_BASIC return Tls12ClientSendFinishedProcess(ctx); #endif /* HITLS_TLS_PROTO_TLS_BASIC */ } #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsServerSendFinishedProcess(ctx); } #endif #ifdef HITLS_TLS_PROTO_TLS_BASIC return Tls12ServerSendFinishedProcess(ctx); #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #endif /* HITLS_TLS_HOST_SERVER */ return HITLS_INTERNAL_EXCEPTION; } static int32_t ProcessSendHandshakeMsg(TLS_Ctx *ctx) { switch (ctx->hsCtx->state) { #ifdef HITLS_TLS_HOST_SERVER #ifdef HITLS_TLS_FEATURE_RENEGOTIATION case TRY_SEND_HELLO_REQUEST: return ServerSendHelloRequestProcess(ctx); #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) case TRY_SEND_HELLO_VERIFY_REQUEST: return DtlsServerSendHelloVerifyRequestProcess(ctx); #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ case TRY_SEND_SERVER_HELLO: return ServerSendServerHelloProcess(ctx); case TRY_SEND_SERVER_KEY_EXCHANGE: return ServerSendServerKeyExchangeProcess(ctx); case TRY_SEND_CERTIFICATE_REQUEST: return ServerSendCertRequestProcess(ctx); case TRY_SEND_SERVER_HELLO_DONE: return ServerSendServerHelloDoneProcess(ctx); #ifdef HITLS_TLS_FEATURE_SESSION_TICKET case TRY_SEND_NEW_SESSION_TICKET: return SendNewSessionTicketProcess(ctx); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #endif /* HITLS_TLS_HOST_SERVER */ #ifdef HITLS_TLS_HOST_CLIENT case TRY_SEND_CLIENT_HELLO: return ClientSendClientHelloProcess(ctx); case TRY_SEND_CLIENT_KEY_EXCHANGE: return ClientSendClientKeyExchangeProcess(ctx); case TRY_SEND_CERTIFICATE_VERIFY: return ClientSendCertVerifyProcess(ctx); #endif /* HITLS_TLS_HOST_CLIENT */ case TRY_SEND_CERTIFICATE: return SendCertificateProcess(ctx); case TRY_SEND_CHANGE_CIPHER_SPEC: return SendChangeCipherSpecProcess(ctx); case TRY_SEND_FINISH: return SendFinishedProcess(ctx); default: break; } BSL_LOG_BINLOG_VARLEN(BINLOG_ID17100, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Handshake state err: should send msg, but current state is %s.", HS_GetStateStr(ctx->hsCtx->state)); return HITLS_MSG_HANDLE_STATE_ILLEGAL; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13SendChangeCipherSpecProcess(TLS_Ctx *ctx) { int32_t ret; /* Sending message with changed cipher suites */ ret = ctx->method.sendCCS(ctx); if (ret != HITLS_SUCCESS) { return ret; } return HS_ChangeState(ctx, ctx->hsCtx->ccsNextState); } static int32_t Tls13ProcessSendHandshakeMsg(TLS_Ctx *ctx) { switch (ctx->hsCtx->state) { #ifdef HITLS_TLS_HOST_CLIENT case TRY_SEND_CLIENT_HELLO: return Tls13ClientSendClientHelloProcess(ctx); #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER case TRY_SEND_HELLO_RETRY_REQUEST: return Tls13ServerSendHelloRetryRequestProcess(ctx); case TRY_SEND_SERVER_HELLO: return Tls13ServerSendServerHelloProcess(ctx); case TRY_SEND_ENCRYPTED_EXTENSIONS: return Tls13ServerSendEncryptedExtensionsProcess(ctx); case TRY_SEND_CERTIFICATE_REQUEST: return Tls13ServerSendCertRequestProcess(ctx); case TRY_SEND_NEW_SESSION_TICKET: return Tls13SendNewSessionTicketProcess(ctx); #endif /* HITLS_TLS_HOST_SERVER */ case TRY_SEND_CERTIFICATE: #ifdef HITLS_TLS_HOST_CLIENT if (ctx->isClient) { return Tls13ClientSendCertificateProcess(ctx); } #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER return Tls13ServerSendCertificateProcess(ctx); #endif /* HITLS_TLS_HOST_SERVER */ case TRY_SEND_CERTIFICATE_VERIFY: return Tls13SendCertVerifyProcess(ctx); case TRY_SEND_FINISH: #ifdef HITLS_TLS_HOST_CLIENT if (ctx->isClient) { return Tls13ClientSendFinishedProcess(ctx); } #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER return Tls13ServerSendFinishedProcess(ctx); #endif /* HITLS_TLS_HOST_SERVER */ case TRY_SEND_CHANGE_CIPHER_SPEC: return Tls13SendChangeCipherSpecProcess(ctx); #ifdef HITLS_TLS_FEATURE_KEY_UPDATE case TRY_SEND_KEY_UPDATE: return Tls13SendKeyUpdateProcess(ctx); #endif default: break; } return RETURN_ERROR_NUMBER_PROCESS(HITLS_MSG_HANDLE_STATE_ILLEGAL, BINLOG_ID17101, "Handshake state error"); } #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t HS_SendMsgProcess(TLS_Ctx *ctx) { uint32_t version = HS_GetVersion(ctx); switch (version) { #ifdef HITLS_TLS_PROTO_TLS_BASIC case HITLS_VERSION_TLS12: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_VERSION_TLCP_DTLCP11: #endif return ProcessSendHandshakeMsg(ctx); #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 case HITLS_VERSION_TLS13: return Tls13ProcessSendHandshakeMsg(ctx); #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_DTLS12 case HITLS_VERSION_DTLS12: return ProcessSendHandshakeMsg(ctx); #endif default: break; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15790, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Handshake state send error: unsupport TLS version.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; }
2301_79861745/bench_create
tls/handshake/send/src/hs_state_send.c
C
unknown
8,501
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" #include "bsl_sal.h" #ifdef HITLS_TLS_FEATURE_PHA #define CERT_REQ_CTX_SIZE 32 #endif /* #ifdef HITLS_TLS_FEATURE_PHA */ static int32_t PackAndSendCertRequest(TLS_Ctx *ctx) { /* get the server infomation */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* determine whether to assemble a message */ if (hsCtx->msgLen == 0) { /* assemble message */ int32_t ret = HS_PackMsg(ctx, CERTIFICATE_REQUEST); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15836, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack certificate request msg fail.", 0, 0, 0, 0); return ret; } } return HS_SendMsg(ctx); } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t ServerSendCertRequestProcess(TLS_Ctx *ctx) { int32_t ret; ret = PackAndSendCertRequest(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15837, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send certificate request msg success.", 0, 0, 0, 0); /* update the state machine */ ctx->hsCtx->isNeedClientCert = true; ctx->negotiatedInfo.certReqSendTime++; return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO_DONE); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13ServerSendCertRequestProcess(TLS_Ctx *ctx) { int32_t ret; #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState == PHA_PENDING) { BSL_SAL_FREE(ctx->certificateReqCtx); ctx->certificateReqCtx = BSL_SAL_Calloc(CERT_REQ_CTX_SIZE, sizeof(uint8_t)); if (ctx->certificateReqCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15630, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cert req ctx malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), ctx->certificateReqCtx, CERT_REQ_CTX_SIZE); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(ctx->certificateReqCtx); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15631, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "generate random cert req ctx fail.", 0, 0, 0, 0); return ret; } ctx->certificateReqCtxSize = CERT_REQ_CTX_SIZE; } #endif /* HITLS_TLS_FEATURE_PHA */ ret = PackAndSendCertRequest(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15838, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send tls1.3 certificate request msg success.", 0, 0, 0, 0); ctx->hsCtx->isNeedClientCert = true; ctx->negotiatedInfo.certReqSendTime++; #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState == PHA_PENDING) { ctx->phaState = PHA_REQUESTED; SAL_CRYPT_DigestFree(ctx->phaCurHash); ctx->phaCurHash = ctx->hsCtx->verifyCtx->hashCtx; ctx->hsCtx->verifyCtx->hashCtx = NULL; return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_FEATURE_PHA */ return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/send/src/send_cert_request.c
C
unknown
4,100
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT) || defined(HITLS_TLS_PROTO_TLS13) #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_verify.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" static int32_t PackAndSendCertVerify(TLS_Ctx *ctx) { int32_t ret; HS_Ctx *hsCtx = ctx->hsCtx; CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; /* determine whether to assemble a message */ if (hsCtx->msgLen == 0) { HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(mgrCtx, false); ret = VERIFY_CalcSignData(ctx, privateKey, ctx->negotiatedInfo.signScheme); if (ret != HITLS_SUCCESS) { return ret; } /* assemble message */ ret = HS_PackMsg(ctx, CERTIFICATE_VERIFY); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15833, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client pack certificate verify msg fail.", 0, 0, 0, 0); return ret; } /* after the signature is used up, the length is set to 0, and the signature is used by the finish */ hsCtx->verifyCtx->verifyDataSize = 0; } return HS_SendMsg(ctx); } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t ClientSendCertVerifyProcess(TLS_Ctx *ctx) { int32_t ret; ret = PackAndSendCertVerify(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15834, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "client send certificate verify msg success.", 0, 0, 0, 0); /* update the state machine */ return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13SendCertVerifyProcess(TLS_Ctx *ctx) { int32_t ret; ret = PackAndSendCertVerify(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15835, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 certificate verify msg success.", 0, 0, 0, 0); return HS_ChangeState(ctx, TRY_SEND_FINISH); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_CLIENT || HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/send/src/send_cert_verify.c
C
unknown
2,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 "hitls_build.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_msg.h" #include "hs_common.h" #include "hs_kx.h" #include "pack.h" #include "send_process.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t SendCertificateProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { /* Only the client can send a certificate message with an empty certificate */ if ((ctx->isClient == false) && (SAL_CERT_GetCurrentCert(mgrCtx) == NULL)) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15760, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "no certificate could be used in server.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE; } ret = HS_PackMsg(ctx, CERTIFICATE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15761, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack certificate msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15762, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send certificate msg success.", 0, 0, 0, 0); if (ctx->isClient) { return HS_ChangeState(ctx, TRY_SEND_CLIENT_KEY_EXCHANGE); } if (IsNeedServerKeyExchange(ctx) == true) { return HS_ChangeState(ctx, TRY_SEND_SERVER_KEY_EXCHANGE); } /* The server sends CertificateRequest only when the isSupportClientVerify mode is enabled */ if (ctx->config.tlsConfig.isSupportClientVerify) { /* isSupportClientOnceVerify specifies whether the CR is sent only in the initial handshake phase. */ /* The value of certReqSendTime indicates the number of sent CR messages. If the value of certReqSendTime in the * renegotiation phase is 0 and isSupportClientOnceVerify is enabled, the CR messages will not be sent. */ if (ctx->negotiatedInfo.certReqSendTime < 1 || !(ctx->config.tlsConfig.isSupportClientOnceVerify)) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_REQUEST); } } return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO_DONE); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 int32_t Tls13ClientSendCertificateProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { /* In the middlebox scenario, if the client does not send the hrr message, a CCS message needs to be sent * before the certificate */ if (ctx->config.tlsConfig.isMiddleBoxCompat && !ctx->hsCtx->haveHrr #ifdef HITLS_TLS_FEATURE_PHA && ctx->phaState != PHA_REQUESTED #endif /* HITLS_TLS_FEATURE_PHA */ ) { ret = ctx->method.sendCCS(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState != PHA_REQUESTED) #endif /* HITLS_TLS_FEATURE_PHA */ { /* CCS messages cannot be encrypted. Therefore, you need to activate the sending key of the client after sending CCS messages. */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17103, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize fail", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } ret = HS_SwitchTrafficKey(ctx, ctx->hsCtx->clientHsTrafficSecret, hashLen, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17104, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SwitchTrafficKey fail", 0, 0, 0, 0); return ret; } } ret = HS_PackMsg(ctx, CERTIFICATE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15763, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack tls1.3 client certificate msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15764, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 client certificate msg success.", 0, 0, 0, 0); /* If the certificate is empty, the certificate verify message does not need to be sent. */ if (SAL_CERT_GetCurrentCert(ctx->config.tlsConfig.certMgrCtx) == NULL) { return HS_ChangeState(ctx, TRY_SEND_FINISH); } return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_VERIFY); } int32_t Tls13ServerSendCertificateProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { /* The server cannot send an empty certificate message */ if (SAL_CERT_GetCurrentCert(ctx->config.tlsConfig.certMgrCtx) == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15765, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "no certificate could be used in server.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE; } ret = HS_PackMsg(ctx, CERTIFICATE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15766, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack server tls1.3 certificate msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15767, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 server certificate msg success.", 0, 0, 0, 0); return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_VERIFY); } #endif /* HITLS_TLS_PROTO_TLS13 */
2301_79861745/bench_create
tls/handshake/send/src/send_certificate.c
C
unknown
7,062
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "rec.h" #include "hs_ctx.h" #include "hs_common.h" #include "send_process.h" int32_t SendChangeCipherSpecProcess(TLS_Ctx *ctx) { int32_t ret; /* send message which changed cipher suites */ ret = ctx->method.sendCCS(ctx); if (ret != HITLS_SUCCESS) { return ret; } /* enable key specification */ ret = REC_ActivePendingState(ctx, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15873, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "active pending fail.", 0, 0, 0, 0); return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15874, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send ccs msg success.", 0, 0, 0, 0); ctx->negotiatedInfo.isEncryptThenMacWrite = ctx->negotiatedInfo.isEncryptThenMac; /* update the state machine */ return HS_ChangeState(ctx, TRY_SEND_FINISH); }
2301_79861745/bench_create
tls/handshake/send/src/send_change_cipher_spec.c
C
unknown
1,587
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #include <string.h> #include "securec.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 "crypt.h" #include "bsl_uio.h" #include "hitls_error.h" #include "hitls_session.h" #include "hitls.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_dtls_timer.h" #include "hs_verify.h" #include "pack.h" #include "send_process.h" #include "session_mgr.h" #include "bsl_bytes.h" #include "config_type.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #ifdef HITLS_TLS_FEATURE_SESSION /* Check whether the resume function is supported */ static int32_t ClientPrepareSession(TLS_Ctx *ctx) { HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* If the session cannot be resumed during renegotiation, delete the session */ if (ctx->negotiatedInfo.isRenegotiation && !ctx->config.tlsConfig.isResumptionOnRenego) { HITLS_SESS_Free(ctx->session); ctx->session = NULL; } if (ctx->session != NULL) { uint64_t curTime = (uint64_t)BSL_SAL_CurrentSysTimeGet(); if (!SESS_CheckValidity(ctx->session, curTime)) { HITLS_SESS_Free(ctx->session); ctx->session = NULL; } } if (ctx->session != NULL) { uint8_t haveExtMasterSecret = 0; HITLS_SESS_GetHaveExtMasterSecret(ctx->session, &haveExtMasterSecret); if (haveExtMasterSecret == 0 && ctx->config.tlsConfig.isSupportExtendMasterSecret) { HITLS_SESS_Free(ctx->session); ctx->session = NULL; return HITLS_SUCCESS; } hsCtx->sessionId = (uint8_t *)BSL_SAL_Calloc(1u, HITLS_SESSION_ID_MAX_SIZE); if (hsCtx->sessionId == NULL) { HITLS_SESS_Free(ctx->session); ctx->session = NULL; BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15624, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "session Id malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } hsCtx->sessionIdSize = HITLS_SESSION_ID_MAX_SIZE; int32_t ret = HITLS_SESS_GetSessionId(ctx->session, hsCtx->sessionId, &hsCtx->sessionIdSize); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(hsCtx->sessionId); HITLS_SESS_Free(ctx->session); ctx->session = NULL; return ret; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION */ static int32_t ClientChangeStateAfterSendClientHello(TLS_Ctx *ctx) { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t ret = HS_StartTimer(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif #ifdef HITLS_TLS_FEATURE_SESSION if (ctx->session != NULL && IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { /* In the DTLS scenario, enable the receiving of CCS messages to prevent CCS message disorder during session * resumption */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); } #endif /* HITLS_TLS_FEATURE_SESSION */ /* TLS and DTLS over SCTP do not need to process the hello_verify_request message */ return HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO); } int32_t ClientSendClientHelloProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain client information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { /* If HelloVerifyRequest is used, the initial ClientHello and HelloVerifyRequest are not included in the calculation of the handshake_messages (for the CertificateVerify message) and verify_data (for the Finished message). */ ret = VERIFY_Init(hsCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17107, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VERIFY_Init fail", 0, 0, 0, 0); return ret; } /* 1. For DTLS, the Hello Verify Request message may be received. If the Client Hello message is sent for the * second time, the random and session of the previous session can be used directly. If the value of cookieSize * is not 0, the Hello Verify Request message is received. * 2. In the renegotiation state, the random and session need to be obtained again */ if ((ctx->negotiatedInfo.cookieSize == 0) || (ctx->negotiatedInfo.isRenegotiation)) { #ifdef HITLS_TLS_FEATURE_SESSION ret = ClientPrepareSession(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_FEATURE_SESSION */ ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->clientRandom, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15625, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "generate random value fail.", 0, 0, 0, 0); return ret; } } ctx->negotiatedInfo.clientVersion = ctx->config.tlsConfig.maxVersion; ret = HS_PackMsg(ctx, CLIENT_HELLO); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15626, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack client hello fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15627, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send client hello success.", 0, 0, 0, 0); return ClientChangeStateAfterSendClientHello(ctx); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static bool Tls13SelectGroup(TLS_Ctx *ctx, uint16_t *firstGroup, uint16_t *secondGroup) { TLS_Config *tlsConfig = &ctx->config.tlsConfig; uint16_t version = (ctx->negotiatedInfo.version == 0) ? ctx->config.tlsConfig.maxVersion : ctx->negotiatedInfo.version; bool isFirstGroupKem = false; uint16_t group1 = HITLS_NAMED_GROUP_BUTT; uint16_t group2 = HITLS_NAMED_GROUP_BUTT; for (uint32_t i = 0; i < tlsConfig->groupsSize; ++i) { const TLS_GroupInfo *groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, tlsConfig->groups[i]); if (groupInfo == NULL) { continue; } if (GroupConformToVersion(ctx, version, tlsConfig->groups[i])) { if (group1 == HITLS_NAMED_GROUP_BUTT) { group1 = tlsConfig->groups[i]; isFirstGroupKem = groupInfo->isKem; continue; /* Prepare one KEM and one KEX keyshare */ } else if (isFirstGroupKem != groupInfo->isKem) { group2 = tlsConfig->groups[i]; break; } } } if (group1 == HITLS_NAMED_GROUP_BUTT) { return false; } *firstGroup = group1; *secondGroup = group2; return true; } static int32_t Tls13ClientGenKeyPair(TLS_Ctx *ctx, KeyExchCtx *kxCtx, uint16_t firstGroup, uint16_t secondGroup) { HITLS_ECParameters curveParams = { .type = HITLS_EC_CURVE_TYPE_NAMED_CURVE, .param.namedcurve = firstGroup, }; // ecdhe and dhe groups can invoke the same interface to generate keys. HITLS_CRYPT_Key *key = SAL_CRYPT_GenEcdhKeyPair(ctx, &curveParams); if (key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15629, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server generate key share key pair error.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } if (kxCtx->key != NULL) { SAL_CRYPT_FreeEcdhKey(kxCtx->key); } kxCtx->key = key; if (kxCtx->secondKey != NULL) { SAL_CRYPT_FreeEcdhKey(kxCtx->secondKey); kxCtx->secondKey = NULL; } if (secondGroup != HITLS_NAMED_GROUP_BUTT) { curveParams.param.namedcurve = secondGroup; HITLS_CRYPT_Key *secondKey = SAL_CRYPT_GenEcdhKeyPair(ctx, &curveParams); if (secondKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15629, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server generate key share key pair error.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } kxCtx->secondKey = secondKey; } return HITLS_SUCCESS; } static int32_t Tls13ClientPrepareKeyShare(TLS_Ctx *ctx, uint32_t tls13BasicKeyExMode) { TLS_Config *tlsConfig = &ctx->config.tlsConfig; // Certificate authentication and PSK with DHE authentication require key share uint32_t needKeyShareMode = TLS13_KE_MODE_PSK_WITH_DHE | TLS13_CERT_AUTH_WITH_DHE; if ((tls13BasicKeyExMode & needKeyShareMode) == 0) { return HITLS_SUCCESS; } if (tlsConfig->groups == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15628, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "tlsConfig->groups is null when prepare key share.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } uint16_t firstGroup = HITLS_NAMED_GROUP_BUTT; uint16_t secondGroup = HITLS_NAMED_GROUP_BUTT; /* The keyShare has passed the verification when receiving the HRR */ KeyShareParam *share = &ctx->hsCtx->kxCtx->keyExchParam.share; if (ctx->hsCtx->haveHrr) { /* If the value of group is not updated in the hello retry request, the system directly returns */ if (share->group == ctx->negotiatedInfo.negotiatedGroup || share->secondGroup == ctx->negotiatedInfo.negotiatedGroup) { return HITLS_SUCCESS; } /* If the value of group is updated, use the updated group */ firstGroup = ctx->negotiatedInfo.negotiatedGroup; secondGroup = HITLS_NAMED_GROUP_BUTT; } else { if (!Tls13SelectGroup(ctx, &firstGroup, &secondGroup)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17109, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SelectGroup fail", 0, 0, 0, 0); return HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP; } /* Send the client hello message for the first time and fill in the group in the key share extension */ } share->group = firstGroup; share->secondGroup = secondGroup; return Tls13ClientGenKeyPair(ctx, ctx->hsCtx->kxCtx, firstGroup, secondGroup); } static int32_t Tls13ClientPrepareSession(TLS_Ctx *ctx) { if (!ctx->config.tlsConfig.isMiddleBoxCompat) { ctx->hsCtx->sessionIdSize = 0; return HITLS_SUCCESS; } int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; hsCtx->sessionId = (uint8_t *)BSL_SAL_Calloc(1u, HITLS_SESSION_ID_MAX_SIZE); if (hsCtx->sessionId == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15630, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "session Id malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->sessionId, HITLS_SESSION_ID_MAX_SIZE); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(hsCtx->sessionId); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15631, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "generate random session Id fail.", 0, 0, 0, 0); return ret; } hsCtx->sessionIdSize = HITLS_SESSION_ID_MAX_SIZE; return HITLS_SUCCESS; } int32_t CreatePskSession(TLS_Ctx *ctx, uint8_t *id, uint32_t idLen, HITLS_Session **pskSession) { if (ctx == NULL || pskSession == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17110, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_NULL_INPUT; } if (ctx->config.tlsConfig.pskClientCb == NULL) { return HITLS_SUCCESS; } uint8_t psk[HS_PSK_MAX_LEN] = {0}; uint32_t pskLen = ctx->config.tlsConfig.pskClientCb(ctx, NULL, id, idLen, psk, HS_PSK_MAX_LEN); if (pskLen == 0) { return HITLS_SUCCESS; } if (pskLen > HS_PSK_MAX_LEN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17111, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pskLen err", 0, 0, 0, 0); memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return HITLS_MSG_HANDLE_ILLEGAL_PSK_LEN; } HITLS_Session *sess = HITLS_SESS_New(); if (sess == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17112, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sess new fail", 0, 0, 0, 0); memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return HITLS_MEMALLOC_FAIL; } HITLS_SESS_SetMasterKey(sess, psk, pskLen); HITLS_SESS_SetCipherSuite(sess, HITLS_AES_128_GCM_SHA256); HITLS_SESS_SetProtocolVersion(sess, HITLS_VERSION_TLS13); *pskSession = sess; memset_s(psk, HS_PSK_MAX_LEN, 0, HS_PSK_MAX_LEN); return HITLS_SUCCESS; } static bool IsTls13SessionValid(HITLS_HashAlgo hashAlgo, HITLS_Session* session, uint16_t *tls13CipherSuites, uint32_t tls13cipherSuitesSize) { uint16_t version = 0; HITLS_SESS_GetProtocolVersion(session, &version); if (version != HITLS_VERSION_TLS13) { return false; } uint16_t cipherSuite = 0; CipherSuiteInfo cipherInfo = {0}; (void)HITLS_SESS_GetCipherSuite(session, &cipherSuite); // only null input cause error int32_t ret = CFG_GetCipherSuiteInfo(cipherSuite, &cipherInfo); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17113, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetCipherSuiteInfo fail", 0, 0, 0, 0); return false; } if (hashAlgo != HITLS_HASH_BUTT) { return (hashAlgo == cipherInfo.hashAlg); } if (tls13CipherSuites != NULL) { for (uint32_t i = 0; i < tls13cipherSuitesSize; i++) { CipherSuiteInfo configCipher = {0}; ret = CFG_GetCipherSuiteInfo(tls13CipherSuites[i], &configCipher); if (ret == HITLS_SUCCESS && configCipher.hashAlg == cipherInfo.hashAlg) { return true; } } } return false; } static UserPskList *ConstructUserPsk(HITLS_Session *sessoin, const uint8_t *identity, uint32_t identityLen, uint8_t curIndex) { if (identityLen > HS_PSK_IDENTITY_MAX_LEN || sessoin == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17114, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "identityLen err or sessoin NULL", 0, 0, 0, 0); return NULL; } UserPskList *userPsk = BSL_SAL_Calloc(1, sizeof(UserPskList)); if (userPsk == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17115, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } userPsk->pskSession = HITLS_SESS_Dup(sessoin); userPsk->identity = BSL_SAL_Calloc(1, identityLen); if (userPsk->identity == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17116, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_SAL_FREE(userPsk); return NULL; } (void)memcpy_s(userPsk->identity, identityLen, identity, identityLen); userPsk->identityLen = identityLen; userPsk->num = curIndex; return userPsk; } static int32_t Tls13ClientPreparePSK(TLS_Ctx *ctx) { int32_t ret = 0; HS_Ctx *hsCtx = ctx->hsCtx; HITLS_HashAlgo hashAlgo = hsCtx->haveHrr ? ctx->negotiatedInfo.cipherSuiteInfo.hashAlg : HITLS_HASH_BUTT; uint8_t identity[HS_PSK_IDENTITY_MAX_LEN + 1] = {0}; const uint8_t *id = NULL; uint32_t idLen = 0; HITLS_Session *pskSession = NULL; UserPskList *userPsk = NULL; /* Obtain the resume psk information from the session */ HITLS_SESS_Free(hsCtx->kxCtx->pskInfo13.resumeSession); hsCtx->kxCtx->pskInfo13.resumeSession = NULL; if (HITLS_SESS_HasTicket(ctx->session) && IsTls13SessionValid(hashAlgo, ctx->session, ctx->config.tlsConfig.tls13CipherSuites, ctx->config.tlsConfig.tls13cipherSuitesSize) && SESS_CheckValidity(ctx->session, (uint64_t)BSL_SAL_CurrentSysTimeGet())) { hsCtx->kxCtx->pskInfo13.resumeSession = HITLS_SESS_Dup(ctx->session); } uint8_t index = (hsCtx->kxCtx->pskInfo13.resumeSession == NULL) ? 0 : 1; if (ctx->config.tlsConfig.pskUseSessionCb != NULL) { ret = ctx->config.tlsConfig.pskUseSessionCb(ctx, hashAlgo, &id, &idLen, &pskSession); if (ret != HITLS_PSK_USE_SESSION_CB_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17117, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pskUseSessionCb fail, ret %d", ret, 0, 0, 0); return HITLS_MSG_HANDLE_PSK_USE_SESSION_FAIL; } } if (pskSession == NULL) { // use 1.2 psk callback default hashalgo == sha256 ret = CreatePskSession(ctx, identity, HS_PSK_IDENTITY_MAX_LEN, &pskSession); if (ret != HITLS_SUCCESS) { return ret; } id = identity; idLen = (uint32_t)strlen((char *)identity); } if (pskSession != NULL && IsTls13SessionValid(hashAlgo, pskSession, ctx->config.tlsConfig.tls13CipherSuites, ctx->config.tlsConfig.tls13cipherSuitesSize)) { userPsk = ConstructUserPsk(pskSession, id, idLen, index); } HITLS_SESS_Free(pskSession); pskSession = NULL; if (ctx->hsCtx->kxCtx->pskInfo13.userPskSess != NULL) { BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo13.userPskSess->identity); HITLS_SESS_Free(ctx->hsCtx->kxCtx->pskInfo13.userPskSess->pskSession); BSL_SAL_FREE(ctx->hsCtx->kxCtx->pskInfo13.userPskSess); } ctx->hsCtx->kxCtx->pskInfo13.userPskSess = userPsk; return HITLS_SUCCESS; } int32_t Tls13ClientHelloPrepare(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; /* After receiving the hello retry request message, the client needs to send the second clientHello. In this case, * the following initialization is not required */ if (hsCtx->haveHrr == false) { ret = VERIFY_Init(hsCtx); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17118, "VERIFY_Init fail"); } ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->clientRandom, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID15632, "generate random value fail"); } /* In section 4.1.2 of RFC8446, a random session ID is required in middlebox mode. In nomiddlebox mode, the * session ID is empty */ ret = Tls13ClientPrepareSession(ctx); if (ret != HITLS_SUCCESS) { return ret; } } else if (ctx->config.tlsConfig.isMiddleBoxCompat) { /* If the middlebox is used, a CCS message must be sent before the second clientHello message is sent */ ret = ctx->method.sendCCS(ctx); if (ret != HITLS_SUCCESS) { return ret; } } ret = Tls13ClientPreparePSK(ctx); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } uint32_t tls13BasicKeyExMode = 0; PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; if (pskInfo->resumeSession != NULL || pskInfo->userPskSess != NULL) { tls13BasicKeyExMode |= ctx->config.tlsConfig.keyExchMode; // keyExchMode must not be 0 } if (ctx->config.tlsConfig.signAlgorithmsSize != 0) { // base cert auth tls13BasicKeyExMode |= TLS13_CERT_AUTH_WITH_DHE; } /* Prepare the key share extension. The keyshares in two clientHello messages are different. Therefore, * both the keyshares must be prepared */ ret = Tls13ClientPrepareKeyShare(ctx, tls13BasicKeyExMode); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } if (tls13BasicKeyExMode == 0) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CONFIG_INVALID_SET, BINLOG_ID16140, "tls config err: can not decide tls13BasicKeyExMode"); } ctx->negotiatedInfo.tls13BasicKeyExMode = tls13BasicKeyExMode; return HITLS_SUCCESS; } static uint32_t GetBindersOffset(const TLS_Ctx *ctx) { uint32_t ret = sizeof(uint16_t); PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; uint32_t binderLen = 0; if (pskInfo->resumeSession != NULL) { HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT; binderLen = HS_GetBinderLen(pskInfo->resumeSession, &hashAlg); // Success guaranteed by the context ret += binderLen + sizeof(uint8_t); } if (pskInfo->userPskSess != NULL) { HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT; binderLen = HS_GetBinderLen(pskInfo->userPskSess->pskSession, &hashAlg); // Success guaranteed by the context ret += binderLen + sizeof(uint8_t); } return ret; } static int32_t PackClientPreSharedKeyBinders(const TLS_Ctx *ctx, uint8_t *buf, uint32_t bufLen) { uint32_t trucatedLen = (bufLen - GetBindersOffset(ctx)); buf = buf + trucatedLen; PskInfo13 *pskInfo = &ctx->hsCtx->kxCtx->pskInfo13; uint32_t offset = sizeof(uint16_t); // skip binders len uint8_t psk[HS_PSK_MAX_LEN] = {0}; uint32_t pskLen = HS_PSK_MAX_LEN; uint32_t binderLen = 0; int32_t ret = HITLS_SUCCESS; if (pskInfo->resumeSession != NULL) { HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT; binderLen = HS_GetBinderLen(pskInfo->resumeSession, &hashAlg); // Success guaranteed by the context buf[offset] = binderLen; offset++; ret = HITLS_SESS_GetMasterKey(pskInfo->resumeSession, psk, &pskLen); if (ret != HITLS_SUCCESS) { return ret; } ret = VERIFY_CalcPskBinder(ctx, hashAlg, false, psk, pskLen, ctx->hsCtx->msgBuf, trucatedLen, &buf[offset], binderLen); BSL_SAL_CleanseData(psk, HS_PSK_MAX_LEN); if (ret != HITLS_SUCCESS) { return ret; } offset += binderLen; } if (pskInfo->userPskSess != NULL) { HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT; pskLen = HS_PSK_MAX_LEN; binderLen = HS_GetBinderLen(pskInfo->userPskSess->pskSession, &hashAlg); // context is guaranteed to succeed buf[offset] = (uint8_t)binderLen; offset++; ret = HITLS_SESS_GetMasterKey(pskInfo->userPskSess->pskSession, psk, &pskLen); if (ret != HITLS_SUCCESS) { return ret; } ret = VERIFY_CalcPskBinder(ctx, hashAlg, true, psk, pskLen, ctx->hsCtx->msgBuf, trucatedLen, &buf[offset], binderLen); BSL_SAL_CleanseData(psk, HS_PSK_MAX_LEN); if (ret != HITLS_SUCCESS) { return ret; } offset += binderLen; } BSL_Uint16ToByte((uint16_t)(offset - sizeof(uint16_t)), &buf[0]); // pack binder len return HITLS_SUCCESS; } int32_t Tls13ClientSendClientHelloProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { ret = Tls13ClientHelloPrepare(ctx); if (ret != HITLS_SUCCESS) { return ret; } ctx->negotiatedInfo.clientVersion = HITLS_VERSION_TLS12; /* The packed message is placed in the hsCtx->msgBuf. The length of the packed message is hsCtx->msgLen, * including the CH message header and body */ ret = HS_PackMsg(ctx, CLIENT_HELLO); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15633, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack tls1.3 client hello fail.", 0, 0, 0, 0); return ret; } if (hsCtx->extFlag.havePreShareKey == true) { /* Calculate the binder */ ret = PackClientPreSharedKeyBinders(ctx, hsCtx->msgBuf, hsCtx->msgLen); if (ret != HITLS_SUCCESS) { return ret; } } #ifdef HITLS_TLS_FEATURE_PHA if (hsCtx->extFlag.havePostHsAuth && ctx->phaState == PHA_NONE) { ctx->phaState = PHA_EXTENSION; } #endif /* HITLS_TLS_FEATURE_PHA */ } if (!ctx->method.isRecvCCS(ctx)) { /* Unencrypted CCS can be received after the first ClientHello is sent or received according to RFC 8446 */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15634, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 client hello success.", 0, 0, 0, 0); return HS_ChangeState(ctx, TRY_RECV_SERVER_HELLO); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/send/src/send_client_hello.c
C
unknown
25,521
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_CLIENT #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #include "securec.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 "hs.h" #include "hs_kx.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" #ifdef HITLS_TLS_SUITE_KX_RSA int32_t GenerateRsaPremasterSecret(TLS_Ctx *ctx) { uint32_t offset = 0; HS_Ctx *hsCtx = ctx->hsCtx; KeyExchCtx *kxCtx = hsCtx->kxCtx; uint8_t *preMasterSecret = kxCtx->keyExchParam.rsa.preMasterSecret; /* The First two bytes are the highest version supported by client */ BSL_Uint16ToByte(ctx->negotiatedInfo.clientVersion, preMasterSecret); offset = sizeof(uint16_t); /* 46-byte secure random value */ return SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), &preMasterSecret[offset], MASTER_SECRET_LEN - offset); } #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_PROTO_TLCP11 int32_t GenerateEccPremasterSecret(TLS_Ctx *ctx) { uint32_t offset = 0; HS_Ctx *hsCtx = ctx->hsCtx; KeyExchCtx *kxCtx = hsCtx->kxCtx; uint8_t *premasterSecret = kxCtx->keyExchParam.ecc.preMasterSecret; /* The First two bytes are the highest version supported by client */ BSL_Uint16ToByte(ctx->config.tlsConfig.maxVersion, premasterSecret); offset = sizeof(uint16_t); /* 46-byte secure random value */ return SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), &premasterSecret[offset], MASTER_SECRET_LEN - offset); } #endif /* Operations required before packaging CKE */ static int32_t PackMsgPrepare(TLS_Ctx *ctx) { int32_t ret = 0; HS_Ctx *hsCtx = ctx->hsCtx; #ifdef HITLS_TLS_SUITE_KX_RSA if (hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_RSA || hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_RSA_PSK) { ret = GenerateRsaPremasterSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17120, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GenerateRsaPremasterSecret fail", 0, 0, 0, 0); (void)memset_s(hsCtx->kxCtx->keyExchParam.rsa.preMasterSecret, MASTER_SECRET_LEN, 0, MASTER_SECRET_LEN); return ret; } } #endif /* HITLS_TLS_SUITE_KX_RSA */ #ifdef HITLS_TLS_FEATURE_PSK /* If the PSK and RSA_PSK cipher suites are used, the server may not send the ServerKeyExchange message. Before * packing the ClientKeyExchange message, check whether the PSK has been obtained */ if (hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_PSK || hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_RSA_PSK) { ret = CheckClientPsk(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17121, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckClientPsk fail", 0, 0, 0, 0); (void)memset_s(hsCtx->kxCtx->keyExchParam.rsa.preMasterSecret, MASTER_SECRET_LEN, 0, MASTER_SECRET_LEN); return ret; } } #endif /* HITLS_TLS_FEATURE_PSK */ #ifdef HITLS_TLS_PROTO_TLCP11 if (hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_ECC) { ret = GenerateEccPremasterSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17122, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GenerateEccPremasterSecret fail", 0, 0, 0, 0); (void)memset_s(hsCtx->kxCtx->keyExchParam.ecc.preMasterSecret, MASTER_SECRET_LEN, 0, MASTER_SECRET_LEN); return ret; } } #endif (void)hsCtx; return ret; } int32_t ClientSendClientKeyExchangeProcess(TLS_Ctx *ctx) { int32_t ret = 0; HS_Ctx *hsCtx = ctx->hsCtx; CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; /* Check whether the message needs to be packed */ if (hsCtx->msgLen == 0) { ret = PackMsgPrepare(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_PackMsg(ctx, CLIENT_KEY_EXCHANGE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15816, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client pack client key exchange msg error.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15817, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "client send client key exchange msg success.", 0, 0, 0, 0); ret = HS_GenerateMasterSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15818, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client generate master secret fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } /* Client derives key */ ret = HS_KeyEstablish(ctx, ctx->isClient); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15819, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client key establish fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) ret = HS_SetSctpAuthKey(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17124, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "SetSctpAuthKey fail", 0, 0, 0, 0); return ret; } #endif /** * If no certificate request is received and no certificate is available, * the system proceeds to the next state. * RFC 5246 7.4.8: This message (here is client certificate verify) is only sent following * a client certificate that has signing capability. * Therefore, the client certificate verify message will not be sent if client certificate is empty. * For TLCP, SAL_CERT_GetCurrentCert MAY return NULL when dealing with cerificate request message, * Whether the client needing to be verified depends on the server configuration. */ if (hsCtx->isNeedClientCert && (SAL_CERT_GetCurrentCert(mgrCtx) != NULL)) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_VERIFY); } return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_CLIENT */
2301_79861745/bench_create
tls/handshake/send/src/send_client_key_exchange.c
C
unknown
6,944
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls.h" #include "hitls_error.h" #include "hitls_config.h" #include "tls.h" #include "rec.h" #include "transcript_hash.h" #include "hs_ctx.h" #include "hs.h" #include "send_process.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif /* HITLS_TLS_FEATURE_INDICATOR */ #ifdef HITLS_TLS_PROTO_TLS static int32_t TlsSendHandShakeMsg(TLS_Ctx *ctx) { HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; int32_t 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_ID17125, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetMaxWriteSize fail", 0, 0, 0, 0); return ret; } do { uint32_t singleWrite = hsCtx->msgLen - hsCtx->msgOffset; singleWrite = (singleWrite > maxRecPayloadLen) ? maxRecPayloadLen : singleWrite; ret = REC_Write(ctx, REC_TYPE_HANDSHAKE, &hsCtx->msgBuf[hsCtx->msgOffset], singleWrite); if (ret != HITLS_SUCCESS) { return ret; } hsCtx->msgOffset += singleWrite; } while (hsCtx->msgOffset != hsCtx->msgLen); hsCtx->msgOffset = 0; /* Add hash data */ ret = VERIFY_Append(hsCtx->verifyCtx, hsCtx->msgBuf, hsCtx->msgLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15795, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "verify append fail when send handshake msg.", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(1, HS_GetVersion(ctx), REC_TYPE_HANDSHAKE, hsCtx->msgBuf, hsCtx->msgLen, ctx, ctx->config.tlsConfig.msgArg); #endif /* HITLS_TLS_FEATURE_INDICATOR */ hsCtx->msgLen = 0; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t HS_DtlsSendFragmentHsMsg(TLS_Ctx *ctx, uint32_t maxRecPayloadLen, const uint8_t *msgData) { int32_t ret = HITLS_SUCCESS; uint8_t *data = (uint8_t *)BSL_SAL_Calloc(1u, maxRecPayloadLen); if (data == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17126, "Calloc fail"); } /* Copy the fragment header */ if (memcpy_s(data, maxRecPayloadLen, msgData, DTLS_HS_MSG_HEADER_SIZE) != EOK) { BSL_SAL_FREE(data); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID15796, "memcpy fail"); } uint32_t fragmentOffset = 0; uint32_t fragmentLen = 0; /* Obtain the length of the handshake msg body */ uint32_t packetLen = BSL_ByteToUint24(&msgData[DTLS_HS_MSGLEN_ADDR]); while (packetLen > 0) { /* Calculate the fragment length */ fragmentLen = packetLen; if (packetLen > (maxRecPayloadLen - DTLS_HS_MSG_HEADER_SIZE)) { fragmentLen = maxRecPayloadLen - DTLS_HS_MSG_HEADER_SIZE; } BSL_Uint24ToByte(fragmentOffset, &data[DTLS_HS_FRAGMENT_OFFSET_ADDR]); BSL_Uint24ToByte(fragmentLen, &data[DTLS_HS_FRAGMENT_LEN_ADDR]); /* Write fragmented data */ if (memcpy_s(&data[DTLS_HS_MSG_HEADER_SIZE], maxRecPayloadLen - DTLS_HS_MSG_HEADER_SIZE, &msgData[DTLS_HS_MSG_HEADER_SIZE + fragmentOffset], fragmentLen) != EOK) { BSL_SAL_FREE(data); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID17127, "memcpy fail"); } /* Send to the record layer */ ret = REC_Write(ctx, REC_TYPE_HANDSHAKE, data, fragmentLen + DTLS_HS_MSG_HEADER_SIZE); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(data); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17128, "Write fail"); } fragmentOffset += fragmentLen; packetLen -= fragmentLen; } BSL_SAL_FREE(data); return ret; } static int32_t SendHsMsgWithPayload(TLS_Ctx *ctx, uint32_t maxRecPayloadLen, HS_Ctx *hsCtx) { int32_t ret = HITLS_SUCCESS; /* No sharding required */ if (maxRecPayloadLen >= hsCtx->msgLen) { /* Send to the record layer */ ret = REC_Write(ctx, REC_TYPE_HANDSHAKE, hsCtx->msgBuf, hsCtx->msgLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15797, 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, hsCtx->msgBuf); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } static int32_t DtlsSendHandShakeMsg(TLS_Ctx *ctx) { int32_t ret; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; #ifdef HITLS_BSL_UIO_UDP ret = REC_QueryMtu(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_BSL_UIO_UDP */ 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_ID17129, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetMaxWriteSize fail", 0, 0, 0, 0); return ret; } ret = SendHsMsgWithPayload(ctx, maxRecPayloadLen, hsCtx); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_BSL_UIO_UDP /* Adding to the retransmission queue */ if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { ret = REC_RetransmitListAppend(ctx->recCtx, REC_TYPE_HANDSHAKE, hsCtx->msgBuf, hsCtx->msgLen); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_BSL_UIO_UDP */ /* Add hash data */ ret = VERIFY_Append(hsCtx->verifyCtx, hsCtx->msgBuf, hsCtx->msgLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15798, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "verify append fail when send handshake msg.", 0, 0, 0, 0); return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(1, HS_GetVersion(ctx), REC_TYPE_HANDSHAKE, hsCtx->msgBuf, hsCtx->msgLen, ctx, ctx->config.tlsConfig.msgArg); #endif /* HITLS_TLS_FEATURE_INDICATOR */ hsCtx->msgLen = 0; hsCtx->nextSendSeq++; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 */ int32_t HS_SendMsg(TLS_Ctx *ctx) { uint32_t version = HS_GetVersion(ctx); switch (version) { #ifdef HITLS_TLS_PROTO_TLS case HITLS_VERSION_TLS12: case HITLS_VERSION_TLS13: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_VERSION_TLCP_DTLCP11: #if defined(HITLS_TLS_PROTO_DTLCP11) if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsSendHandShakeMsg(ctx); } #endif #endif return TlsSendHandShakeMsg(ctx); #endif /* HITLS_TLS_PROTO_TLS */ #ifdef HITLS_TLS_PROTO_DTLS12 case HITLS_VERSION_DTLS12: return DtlsSendHandShakeMsg(ctx); #endif default: break; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15799, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Send handshake msg of unsupported version.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; }
2301_79861745/bench_create
tls/handshake/send/src/send_common.c
C
unknown
8,125
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_TLS13) && defined(HITLS_TLS_HOST_SERVER) #include <stdint.h> #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "crypt.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_kx.h" #include "hs_common.h" #include "hs_msg.h" #include "pack.h" #include "send_process.h" int32_t Tls13ServerSendEncryptedExtensionsProcess(TLS_Ctx *ctx) { int32_t ret; /* Obtain the client information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { /* The CCS message cannot be encrypted. Therefore, the sending key of the server must be activated after the CCS * message is sent */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17130, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize fail", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } ret = HS_SwitchTrafficKey(ctx, ctx->hsCtx->serverHsTrafficSecret, hashLen, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17131, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SwitchTrafficKey fail", 0, 0, 0, 0); return ret; } ret = HS_PackMsg(ctx, ENCRYPTED_EXTENSIONS); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15875, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack tls1.3 encrypted extensions fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15876, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 encrypted extensions success.", 0, 0, 0, 0); if (ctx->hsCtx->kxCtx->pskInfo13.psk != NULL) { return HS_ChangeState(ctx, TRY_SEND_FINISH); } /* The server sends a CertificateRequest message only when the VerifyPeer mode is enabled */ if (ctx->config.tlsConfig.isSupportClientVerify #ifdef HITLS_TLS_FEATURE_PHA && ctx->phaState != PHA_EXTENSION #endif /* HITLS_TLS_FEATURE_PHA */ ) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_REQUEST); } return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE); } #endif /* HITLS_TLS_PROTO_TLS13 && HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/send/src/send_encrypted_extensions.c
C
unknown
3,086
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_verify.h" #include "transcript_hash.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" #include "hs_kx.h" #include "hs_dtls_timer.h" #ifdef HITLS_TLS_HOST_CLIENT #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t PrepareClientFinishedMsg(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; ret = VERIFY_CalcVerifyData(ctx, true, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15357, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client Calculate client finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); (void)memset_s(ctx->hsCtx->masterKey, sizeof(ctx->hsCtx->masterKey), 0, sizeof(ctx->hsCtx->masterKey)); return ret; } ret = HS_PackMsg(ctx, FINISHED); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15358, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client pack finished msg error.", 0, 0, 0, 0); } return ret; } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS_BASIC int32_t Tls12ClientSendFinishedProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; /* Determine whether the message needs to be packed. */ if (hsCtx->msgLen == 0) { ret = PrepareClientFinishedMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15359, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client send finished msg error.", 0, 0, 0, 0); return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15360, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "client send finished msg success.", 0, 0, 0, 0); #ifdef HITLS_TLS_FEATURE_SESSION if (ctx->negotiatedInfo.isResume == true) { ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_FEATURE_SESSION */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET if (ctx->negotiatedInfo.isTicket == true) { return HS_ChangeState(ctx, TRY_RECV_NEW_SESSION_TICKET); } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ ret = VERIFY_CalcVerifyData(ctx, false, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15361, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client Calculate server finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_DTLS12 static int32_t DtlsClientChangeStateAfterSendFinished(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_SESSION if (ctx->negotiatedInfo.isResume == true) { ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); #ifdef HITLS_BSL_UIO_UDP ret = HS_Start2MslTimer(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17133, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Start2MslTimer fail", 0, 0, 0, 0); return ret; } #endif /* HITLS_BSL_UIO_UDP */ return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_FEATURE_SESSION */ ret = VERIFY_CalcVerifyData(ctx, false, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15367, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client Calculate server finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } #ifdef HITLS_BSL_UIO_UDP ret = HS_StartTimer(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17134, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StartTimer fail", 0, 0, 0, 0); return ret; } #endif /* HITLS_BSL_UIO_UDP */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET if (ctx->negotiatedInfo.isTicket == true) { return HS_ChangeState(ctx, TRY_RECV_NEW_SESSION_TICKET); } #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); return HS_ChangeState(ctx, TRY_RECV_FINISH); } int32_t DtlsClientSendFinishedProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { ret = PrepareClientFinishedMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15370, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "client send finished msg success.", 0, 0, 0, 0); return DtlsClientChangeStateAfterSendFinished(ctx); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13ClientSendFinishPostProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState == PHA_REQUESTED) { ctx->phaState = PHA_EXTENSION; } else #endif /* HITLS_TLS_FEATURE_PHA */ { /* switch Application Traffic Secret */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17136, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize fail", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } ret = HS_SwitchTrafficKey(ctx, ctx->clientAppTrafficSecret, hashLen, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17137, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SwitchTrafficKey fail", 0, 0, 0, 0); return ret; } ret = HS_TLS13DeriveResumptionMasterSecret(ctx); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_PHA if (ctx->phaState == PHA_EXTENSION && ctx->config.tlsConfig.isSupportPostHandshakeAuth) { SAL_CRYPT_DigestFree(ctx->phaHash); ctx->phaHash = SAL_CRYPT_DigestCopy(ctx->hsCtx->verifyCtx->hashCtx); if (ctx->phaHash == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_DIGEST); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16177, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pha hash copy error: digest copy fail.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } } #endif /* HITLS_TLS_FEATURE_PHA */ } return HS_ChangeState(ctx, TLS_CONNECTED); } int32_t Tls13ClientSendFinishedProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { if ((ctx->config.tlsConfig.isMiddleBoxCompat && (!ctx->hsCtx->haveHrr)) && (!ctx->hsCtx->isNeedClientCert)) { /* In the middlebox scenario, if the client does not send the hrr message and the certificate does not need * to be sent, a CCS message needs to be sent before the finished message */ ret = ctx->method.sendCCS(ctx); if (ret != HITLS_SUCCESS) { return ret; } } /* If the certificate of the client is sent, the key has been activated when the certificate is sent. You do not * need to activate the key again */ if (!ctx->hsCtx->isNeedClientCert #ifdef HITLS_TLS_FEATURE_PHA && ctx->phaState != PHA_REQUESTED #endif /* HITLS_TLS_FEATURE_PHA */ ) { /* The CCS message cannot be encrypted. Therefore, the sending key of the client must be activated * after the CCS message is sent */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17138, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize fail", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } ret = HS_SwitchTrafficKey(ctx, ctx->hsCtx->clientHsTrafficSecret, hashLen, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17139, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SwitchTrafficKey fail", 0, 0, 0, 0); return ret; } } ret = VERIFY_Tls13CalcVerifyData(ctx, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15375, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client calculate client finished data fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ret = HS_PackMsg(ctx, FINISHED); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15376, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client pack tls1.3 finished msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15377, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "client send tls1.3 finished msg success.", 0, 0, 0, 0); return Tls13ClientSendFinishPostProcess(ctx); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_CLIENT */ #ifdef HITLS_TLS_HOST_SERVER #ifdef HITLS_TLS_PROTO_TLS_BASIC static int32_t CalcVerifyData(TLS_Ctx *ctx) { int32_t ret = VERIFY_CalcVerifyData(ctx, false, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15362, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server Calculate server finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); } return ret; } int32_t Tls12ServerSendFinishedProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { ret = CalcVerifyData(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_PackMsg(ctx, FINISHED); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15363, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack finished msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15364, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server send finished msg fail.", 0, 0, 0, 0); return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15365, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send finished msg success.", 0, 0, 0, 0); #ifdef HITLS_TLS_FEATURE_SESSION if (ctx->negotiatedInfo.isResume == true) { ret = VERIFY_CalcVerifyData(ctx, true, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15366, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server Calculate client finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); (void)memset_s(ctx->hsCtx->masterKey, sizeof(ctx->hsCtx->masterKey), 0, sizeof(ctx->hsCtx->masterKey)); return ret; } ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_FEATURE_SESSION */ /* No CCS messages can be received */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_DTLS12 static int32_t DtlsServerChangeStateAfterSendFinished(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; (void)ret; #ifdef HITLS_TLS_FEATURE_SESSION if (ctx->negotiatedInfo.isResume == true) { /* Calculate the client verify data: used to verify the finished message of the client */ ret = VERIFY_CalcVerifyData(ctx, true, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15371, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server Calculate client finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); (void)memset_s(ctx->hsCtx->masterKey, sizeof(ctx->hsCtx->masterKey), 0, sizeof(ctx->hsCtx->masterKey)); return ret; } ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_ACTIVE_CIPHER_SPEC); #ifdef HITLS_BSL_UIO_UDP ret = HS_StartTimer(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17141, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StartTimer fail", 0, 0, 0, 0); return ret; } #endif /* HITLS_BSL_UIO_UDP */ return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_FEATURE_SESSION */ /* No CCS messages can be received */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_EXIT_READY); #ifdef HITLS_BSL_UIO_UDP ret = HS_Start2MslTimer(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17142, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Start2MslTimer fail", 0, 0, 0, 0); return ret; } #endif /* HITLS_BSL_UIO_UDP */ return HS_ChangeState(ctx, TLS_CONNECTED); } int32_t DtlsServerSendFinishedProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { ret = VERIFY_CalcVerifyData(ctx, false, ctx->hsCtx->masterKey, MASTER_SECRET_LEN); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15372, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server Calculate server finished data error.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ret = HS_PackMsg(ctx, FINISHED); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15373, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack finished msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15374, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send finished msg success.", 0, 0, 0, 0); return DtlsServerChangeStateAfterSendFinished(ctx); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t PrepareServerSendFinishedMsg(TLS_Ctx *ctx) { int32_t ret = VERIFY_Tls13CalcVerifyData(ctx, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15378, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server calculate server finished data fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ret = HS_PackMsg(ctx, FINISHED); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15379, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack tls1.3 finished msg fail.", 0, 0, 0, 0); } return ret; } int32_t Tls13ServerSendFinishedProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { ret = PrepareServerSendFinishedMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15380, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send tls1.3 finished msg success.", 0, 0, 0, 0); ret = HS_TLS13CalcServerFinishProcessSecret(ctx); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17145, "CalcServerFinishProcessSecret fail"); } /* After the server sends the ServerFinish message, the clientTrafficSecret needs to be activated for decryption of * the received packet from the peer */ uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CRYPT_ERR_DIGEST, BINLOG_ID17146, "DigestSize fail"); } ret = HS_SwitchTrafficKey(ctx, ctx->hsCtx->clientHsTrafficSecret, hashLen, false); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17147, "SwitchTrafficKey fail"); } /* Activating the local serverAppTrafficSecret-encrypted App Data */ ret = HS_SwitchTrafficKey(ctx, ctx->serverAppTrafficSecret, hashLen, true); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17148, "SwitchTrafficKey fail"); } if (ctx->hsCtx->isNeedClientCert) { return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE); } /* Calculate the client verify data */ ret = VERIFY_Tls13CalcVerifyData(ctx, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15381, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server calculate client finished data fail.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/send/src/send_finished.c
C
unknown
19,407
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_FEATURE_RENEGOTIATION #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_verify.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" int32_t ServerSendHelloRequestProcess(TLS_Ctx *ctx) { int32_t ret; /* get the server infomation */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* determine whether to assemble a message */ if (hsCtx->msgLen == 0) { /* assemble message */ ret = HS_PackMsg(ctx, HELLO_REQUEST); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15906, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack hello request msg fail.", 0, 0, 0, 0); return ret; } } /* writing handshake message */ ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } /* hash calculation is not required for HelloRequest messages */ ret = VERIFY_Init(hsCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17150, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VERIFY_Init fail", 0, 0, 0, 0); return ret; } /* The server does not enter the renegotiation state when sending a HelloRequest message. The server enters the renegotiation state only when receiving a ClientHello message. */ ctx->negotiatedInfo.isRenegotiation = false; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15907, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send hello request msg success.", 0, 0, 0, 0); return HS_ChangeState(ctx, TLS_CONNECTED); } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */
2301_79861745/bench_create
tls/handshake/send/src/send_hello_request.c
C
unknown
2,313
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER) && defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_verify.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" int32_t DtlsServerSendHelloVerifyRequestProcess(TLS_Ctx *ctx) { int32_t ret; /** get the server infomation */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /** determine whether to assemble a message */ if (hsCtx->msgLen == 0) { /* assemble message */ ret = HS_PackMsg(ctx, HELLO_VERIFY_REQUEST); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17333, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack hello verify request msg fail.", 0, 0, 0, 0); return ret; } } /** writing handshake message */ ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } /* If HelloVerifyRequest is used, the initial ClientHello and HelloVerifyRequest are not included in the calculation of the handshake_messages (for the CertificateVerify message) and verify_data (for the Finished message). */ ret = VERIFY_Init(hsCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17152, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "VERIFY_Init fail", 0, 0, 0, 0); return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17334, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send hello verify request msg success.", 0, 0, 0, 0); /* The reason for clearing the retransmission queue is that the HelloVerifyRequest message does not need to be retransmitted. */ REC_RetransmitListClean(ctx->recCtx); return HS_ChangeState(ctx, TRY_RECV_CLIENT_HELLO); } #endif /* defined(HITLS_TLS_HOST_SERVER) && defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) */
2301_79861745/bench_create
tls/handshake/send/src/send_hello_verify_request.c
C
unknown
2,604
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_TLS_FEATURE_SESSION_TICKET) && defined(HITLS_TLS_HOST_SERVER) #include "securec.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 "bsl_sal.h" #include "hitls_error.h" #include "rec.h" #include "hs_ctx.h" #include "hs_kx.h" #include "hs_common.h" #include "session_mgr.h" #include "pack.h" #include "send_process.h" #ifdef HITLS_TLS_PROTO_TLS13 #define HITLS_ONE_WEEK_SECONDS (604800) #endif #ifdef HITLS_TLS_PROTO_TLS_BASIC int32_t SendNewSessionTicketProcess(TLS_Ctx *ctx) { int32_t ret; HS_Ctx *hsCtx = ctx->hsCtx; TLS_SessionMgr *sessMgr = ctx->config.tlsConfig.sessMgr; /* determine whether to assemble a message */ if (hsCtx->msgLen == 0) { hsCtx->ticketLifetimeHint = (uint32_t)SESSMGR_GetTimeout(sessMgr); BSL_SAL_FREE(hsCtx->ticket); hsCtx->ticketSize = 0; ret = SESSMGR_EncryptSessionTicket(ctx, sessMgr, ctx->session, &hsCtx->ticket, &hsCtx->ticketSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16046, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESSMGR_EncryptSessionTicket return fail when send new session ticket msg.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } /* assemble message */ ret = HS_PackMsg(ctx, NEW_SESSION_TICKET); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15978, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack new session ticket msg fail.", 0, 0, 0, 0); return ret; } } /* writing Handshake message */ ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15979, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send new session ticket msg success.", 0, 0, 0, 0); /* update the state machine */ return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } #endif /* HITLS_TLS_PROTO_TLS_BASIC */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13TicketGenerateConfigSession(TLS_Ctx *ctx, HITLS_Session **sessionPtr, uint8_t *resumePsk, uint32_t hashLen) { int32_t ret = HITLS_SUCCESS; HITLS_Session *newSession = NULL; HS_Ctx *hsCtx = ctx->hsCtx; newSession = SESS_Copy(ctx->session); if (newSession == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16050, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy session info failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return HITLS_MEMALLOC_FAIL; } SESS_SetStartTime(newSession, (uint64_t)BSL_SAL_CurrentSysTimeGet()); HITLS_SESS_SetTimeout(newSession, (uint64_t)hsCtx->ticketLifetimeHint); HITLS_SESS_SetMasterKey(newSession, resumePsk, hashLen); ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), (uint8_t *)&hsCtx->ticketAgeAdd, sizeof(hsCtx->ticketAgeAdd)); if (ret != HITLS_SUCCESS) { HITLS_SESS_Free(newSession); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16047, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "generate ticket_age_add value fail.", 0, 0, 0, 0); return ret; } SESS_SetTicketAgeAdd(newSession, hsCtx->ticketAgeAdd); *sessionPtr = newSession; return HITLS_SUCCESS; } int32_t Tls13TicketGenerate(TLS_Ctx *ctx) { int32_t ret; HITLS_Session *newSession = NULL; HS_Ctx *hsCtx = ctx->hsCtx; TLS_SessionMgr *sessMgr = ctx->config.tlsConfig.sessMgr; uint64_t timeout = SESSMGR_GetTimeout(sessMgr); /* TLS1.3 timeout period cannot exceed 604800 seconds, that is, seven days. */ if (timeout > HITLS_ONE_WEEK_SECONDS) { hsCtx->ticketLifetimeHint = HITLS_ONE_WEEK_SECONDS; } else { hsCtx->ticketLifetimeHint = (uint32_t)timeout; } BSL_SAL_FREE(hsCtx->ticket); hsCtx->ticketSize = 0; uint8_t resumePsk[MAX_DIGEST_SIZE] = {0}; uint32_t hashLen = SAL_CRYPT_DigestSize(ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (hashLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17154, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint8_t ticketNonce[sizeof(hsCtx->nextTicketNonce)] = {0}; BSL_Uint64ToByte(hsCtx->nextTicketNonce, ticketNonce); ret = HS_TLS13DeriveResumePsk(ctx, ticketNonce, sizeof(ticketNonce), resumePsk, hashLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17155, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DeriveResumePsk fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); (void)memset_s(resumePsk, MAX_DIGEST_SIZE, 0, MAX_DIGEST_SIZE); return ret; } ret = Tls13TicketGenerateConfigSession(ctx, &newSession, resumePsk, hashLen); if (ret != HITLS_SUCCESS) { (void)memset_s(resumePsk, MAX_DIGEST_SIZE, 0, MAX_DIGEST_SIZE); return ret; } ret = SESSMGR_EncryptSessionTicket(ctx, sessMgr, newSession, &hsCtx->ticket, &hsCtx->ticketSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16051, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Encrypt Session Ticket failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); HITLS_SESS_Free(newSession); (void)memset_s(resumePsk, MAX_DIGEST_SIZE, 0, MAX_DIGEST_SIZE); return ret; } HITLS_SESS_Free(ctx->session); ctx->session = newSession; (void)memset_s(resumePsk, MAX_DIGEST_SIZE, 0, MAX_DIGEST_SIZE); return HITLS_SUCCESS; } int32_t Tls13SendNewSessionTicketProcess(TLS_Ctx *ctx) { int32_t ret; HS_Ctx *hsCtx = ctx->hsCtx; /* determine whether to assemble a message */ if (hsCtx->msgLen == 0) { ret = Tls13TicketGenerate(ctx); if (ret != HITLS_SUCCESS) { return ret; } /* assemble message */ ret = HS_PackMsg(ctx, NEW_SESSION_TICKET); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16052, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack new session ticket msg fail.", 0, 0, 0, 0); return ret; } } /* After the handshake message is written and sent successfully, hsCtx->msgLen is set to 0. */ ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16053, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send new session ticket msg success.", 0, 0, 0, 0); hsCtx->sentTickets++; hsCtx->nextTicketNonce++; /* When the value of ticketNums is greater than 0, a ticket is sent after the session is resumed. */ if (hsCtx->sentTickets >= ctx->config.tlsConfig.ticketNums || ctx->negotiatedInfo.isResume) { return HS_ChangeState(ctx, TLS_CONNECTED); } return HS_ChangeState(ctx, TRY_SEND_NEW_SESSION_TICKET); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_FEATURE_SESSION_TICKET && HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/send/src/send_new_session_ticket.c
C
unknown
7,743
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 SEND_PROCESS_H #define SEND_PROCESS_H #include <stdint.h> #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Send a handshake message * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval HITLS_UNREGISTERED_CALLBACK * @retval HITLS_CRYPT_ERR_DIGEST hash operation failed * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_MEMALLOC_FAIL Memory allocation failed * @return For details, see REC_Write */ int32_t HS_SendMsg(TLS_Ctx *ctx); /** * @brief Server sends Hello Request messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t ServerSendHelloRequestProcess(TLS_Ctx *ctx); /** * @brief Server sends Hello Verify Request messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t DtlsServerSendHelloVerifyRequestProcess(TLS_Ctx *ctx); /** * @brief Client sends client hello messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t ClientSendClientHelloProcess(TLS_Ctx *ctx); /** * @brief Server sends server hello messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t ServerSendServerHelloProcess(TLS_Ctx *ctx); /** * @brief send certificate messsage * @attention The certificates sent by client and server are the same, except for the processing empty certificates * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t SendCertificateProcess(TLS_Ctx *ctx); /** * @brief Server sends server keyExchange messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t ServerSendServerKeyExchangeProcess(TLS_Ctx *ctx); /** * @brief Server sends server certificate request messsage * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t ServerSendCertRequestProcess(TLS_Ctx *ctx); /** * @brief Server sends server hello done message * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t ServerSendServerHelloDoneProcess(TLS_Ctx *ctx); /** * @brief Client sends client key exchange messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t ClientSendClientKeyExchangeProcess(TLS_Ctx *ctx); /** * @brief Client sends client certificate verify messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t ClientSendCertVerifyProcess(TLS_Ctx *ctx); /** * @brief Server sends ccs messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t SendChangeCipherSpecProcess(TLS_Ctx *ctx); /** * @brief Server sends new session messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t SendNewSessionTicketProcess(TLS_Ctx *ctx); /** * @brief TLS1.3 Server sends new session messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ int32_t Tls13SendNewSessionTicketProcess(TLS_Ctx *ctx); int32_t Tls12ClientSendFinishedProcess(TLS_Ctx *ctx); int32_t Tls12ServerSendFinishedProcess(TLS_Ctx *ctx); /** * @brief Client sends finished messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsClientSendFinishedProcess(TLS_Ctx *ctx); #endif /** * @brief Server sends dtls finished messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @return For details, see hitls_error.h */ #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsServerSendFinishedProcess(TLS_Ctx *ctx); #endif /** * @brief TLS 1.3 Client sends client hello messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ClientSendClientHelloProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Server sends hello retry request messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ServerSendHelloRetryRequestProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Server sends server hello messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ServerSendServerHelloProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Server sends encrypted extensions messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ServerSendEncryptedExtensionsProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Server sends certificate request messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ServerSendCertRequestProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Client sends certificate messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ClientSendCertificateProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Server sends certificate messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ServerSendCertificateProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 send certificate verify messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13SendCertVerifyProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Server sends finished messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ServerSendFinishedProcess(TLS_Ctx *ctx); /** * @brief TLS 1.3 Client sends finished messsage * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS * @retval For details, see hitls_error.h */ int32_t Tls13ClientSendFinishedProcess(TLS_Ctx *ctx); #ifdef __cplusplus } #endif #endif
2301_79861745/bench_create
tls/handshake/send/src/send_process.h
C
unknown
6,989
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #include "securec.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 "crypt.h" #include "hitls_error.h" #include "tls.h" #include "hs.h" #include "hs_ctx.h" #include "session_mgr.h" #include "hs_verify.h" #include "transcript_hash.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" #include "hs_kx.h" #include "config_type.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #ifdef HITLS_TLS_FEATURE_SESSION static int32_t ServerPrepareSessionId(TLS_Ctx *ctx) { /* Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; hsCtx->sessionId = (uint8_t *)BSL_SAL_Calloc(1u, HITLS_SESSION_ID_MAX_SIZE); if (hsCtx->sessionId == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15546, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "session Id malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } if (ctx->negotiatedInfo.isResume == false) { HITLS_SESS_CACHE_MODE sessCacheMode = SESSMGR_GetCacheMode(ctx->config.tlsConfig.sessMgr); bool needSessionId = (sessCacheMode == HITLS_SESS_CACHE_SERVER || sessCacheMode == HITLS_SESS_CACHE_BOTH) && (!ctx->negotiatedInfo.isTicket); if (needSessionId) { hsCtx->sessionIdSize = HITLS_SESSION_ID_MAX_SIZE; int32_t ret = SESSMGR_GernerateSessionId(ctx, hsCtx->sessionId, hsCtx->sessionIdSize); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(hsCtx->sessionId); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } } else { /* If session ID resumption is not supported, the session ID is not sent when the first connection * is established */ BSL_SAL_FREE(hsCtx->sessionId); hsCtx->sessionIdSize = 0; } } else { /* If the session is resumed, obtain the session ID from the session. * In the session ticket resumption mode, the session ID may not be obtained. Therefore, the return value is * not checked */ hsCtx->sessionIdSize = HITLS_SESSION_ID_MAX_SIZE; HITLS_SESS_GetSessionId(ctx->session, hsCtx->sessionId, &hsCtx->sessionIdSize); if (hsCtx->sessionIdSize == 0) { BSL_SAL_FREE(hsCtx->sessionId); } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION */ static int32_t ServerChangeStateAfterSendHello(TLS_Ctx *ctx) { #ifdef HITLS_TLS_FEATURE_SESSION int32_t ret = HITLS_SUCCESS; if (ctx->negotiatedInfo.isResume == true) { ret = HS_ResumeKeyEstablish(ctx); if (ret != HITLS_SUCCESS) { return ret; } if (ctx->negotiatedInfo.isTicket) { return HS_ChangeState(ctx, TRY_SEND_NEW_SESSION_TICKET); } return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } #endif /* HITLS_TLS_FEATURE_SESSION */ /* Check whether the server sends the certificate message. If the server does not need to send the certificate * message, update the status to the server key exchange */ if (IsNeedCertPrepare(&ctx->negotiatedInfo.cipherSuiteInfo) == false) { #ifdef HITLS_TLS_FEATURE_PSK /* There are multiple possible jumps after the ServerHello in the plain PSK negotiation */ if (ctx->hsCtx->kxCtx->keyExchAlgo == HITLS_KEY_EXCH_PSK) { /* Special: If the server does not send the certificate and the plain PSK negotiation mode is used, the * system determines whether to send the SKE by checking whether the hint exists. There are multiple * redirection scenarios. */ /* In the scenario of RSA PSK negotiation, whether SKE messages are sent depends on the existence of hints. * If RSA is used, the certificate sending phase is entered. The SKE status transition is not performed here */ if (ctx->config.tlsConfig.pskIdentityHint != NULL) { return HS_ChangeState(ctx, TRY_SEND_SERVER_KEY_EXCHANGE); } return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO_DONE); } #endif /* HITLS_TLS_FEATURE_PSK */ return HS_ChangeState(ctx, TRY_SEND_SERVER_KEY_EXCHANGE); } return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE); } #if defined(HITLS_TLS_PROTO_TLS13) && defined(HITLS_TLS_PROTO_TLS_BASIC) static int32_t DowngradeServerRandom(TLS_Ctx *ctx) { /* Obtain server information */ int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; uint32_t downgradeRandomLen = 0; uint32_t offset = 0; /* Obtain the random part to be rewritten */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS12) { const uint8_t *downgradeRandom = HS_GetTls12DowngradeRandom(&downgradeRandomLen); /* Some positions need to be rewritten to obtain random */ offset = HS_RANDOM_SIZE - downgradeRandomLen; /* Rewrite the last eight bytes of the random */ ret = memcpy_s(hsCtx->serverRandom + offset, HS_RANDOM_DOWNGRADE_SIZE, downgradeRandom, downgradeRandomLen); } return ret; } #endif /* HITLS_TLS_PROTO_TLS13 && HITLS_TLS_PROTO_TLS_BASIC */ int32_t ServerSendServerHelloProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether to pack a message */ if (hsCtx->msgLen == 0) { #ifdef HITLS_TLS_FEATURE_SESSION ret = ServerPrepareSessionId(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->serverRandom, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15548, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get server random error.", 0, 0, 0, 0); return ret; } #if defined(HITLS_TLS_PROTO_TLS13) && defined(HITLS_TLS_PROTO_TLS_BASIC) TLS_Config *tlsConfig = &ctx->config.tlsConfig; /* If TLS 1.3 is supported but an earlier version is negotiated, the last eight bits of the random number need * to be rewritten */ if (tlsConfig->maxVersion == HITLS_VERSION_TLS13) { ret = DowngradeServerRandom(ctx); if (ret != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16248, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy down grade random fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } } #endif /* HITLS_TLS_PROTO_TLS13 && HITLS_TLS_PROTO_TLS_BASIC */ /* Set the verify information. */ ret = VERIFY_SetHash(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hsCtx->verifyCtx, ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15549, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set verify info fail.", 0, 0, 0, 0); return ret; } ret = HS_PackMsg(ctx, SERVER_HELLO); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15550, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack server hello msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15551, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send server hello msg success.", 0, 0, 0, 0); return ServerChangeStateAfterSendHello(ctx); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS13 static int32_t Tls13ServerPrepareKeyShare(TLS_Ctx *ctx) { KeyShareParam *keyShare = &ctx->hsCtx->kxCtx->keyExchParam.share; KeyExchCtx *kxCtx = ctx->hsCtx->kxCtx; if ((kxCtx->peerPubkey == NULL) || /* If the peer public key is empty, keyshare does not need to be packed */ (kxCtx->key != NULL)) { /* key is not empty, it indicates that the keyshare has been calculated and does not need to be calculated again */ return HITLS_SUCCESS; } const TLS_GroupInfo *groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, keyShare->group); if (groupInfo == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16243, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "group info not found", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } if (groupInfo->isKem) { return HITLS_SUCCESS; } HITLS_ECParameters curveParams = { .type = HITLS_EC_CURVE_TYPE_NAMED_CURVE, .param.namedcurve = keyShare->group, }; HITLS_CRYPT_Key *key = NULL; /* The ecdhe and dhe groups can invoke the same interface to generate keys. */ key = SAL_CRYPT_GenEcdhKeyPair(ctx, &curveParams); if (key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15552, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client generate key share key pair error.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } kxCtx->key = key; return HITLS_SUCCESS; } int32_t Tls13ServerSendServerHelloProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether to pack a message */ if (hsCtx->msgLen == 0) { ret = Tls13ServerPrepareKeyShare(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), hsCtx->serverRandom, HS_RANDOM_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15553, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get server random error.", 0, 0, 0, 0); return ret; } /* Set the verify information */ ret = VERIFY_SetHash(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hsCtx->verifyCtx, ctx->negotiatedInfo.cipherSuiteInfo.hashAlg); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15554, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set verify info fail.", 0, 0, 0, 0); return ret; } /* Server secret derivation */ ret = HS_TLS13CalcServerHelloProcessSecret(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16190, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Derive-Sevret failed.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return ret; } ret = HS_PackMsg(ctx, SERVER_HELLO); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15555, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack tls1.3 server hello msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_TLS13DeriveHandshakeTrafficSecret(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15556, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 server hello msg success.", 0, 0, 0, 0); /* In the middlebox mode, If the scenario is not hrr, the CCS needs to be sent before the EE */ if (ctx->config.tlsConfig.isMiddleBoxCompat && !ctx->hsCtx->haveHrr) { ctx->hsCtx->ccsNextState = TRY_SEND_ENCRYPTED_EXTENSIONS; return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } return HS_ChangeState(ctx, TRY_SEND_ENCRYPTED_EXTENSIONS); } int32_t Tls13ServerSendHelloRetryRequestProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Obtain the server information */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; hsCtx->haveHrr = true; /* update state */ /* Check whether the message needs to be packed */ if (hsCtx->msgLen == 0) { uint32_t hrrRandomLen = 0; const uint8_t *hrrRandom = HS_GetHrrRandom(&hrrRandomLen); if (memcpy_s(hsCtx->serverRandom, HS_RANDOM_SIZE, hrrRandom, hrrRandomLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15557, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "copy hello retry request random fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } /* Pack the message. The hello retry request is assembled in the server hello format */ ret = HS_PackMsg(ctx, SERVER_HELLO); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15558, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pack tls1.3 hello retry request msg fail.", 0, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15559, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "send tls1.3 hello retry request msg success.", 0, 0, 0, 0); /* RFC 8446 4.4.1. Send the Hello Retry Request message and construct the Transcript-Hash data */ ret = VERIFY_HelloRetryRequestVerifyProcess(ctx); if (ret != HITLS_SUCCESS) { return ret; } if (!ctx->config.tlsConfig.isMiddleBoxCompat) { return HS_ChangeState(ctx, TRY_RECV_CLIENT_HELLO); } /* In middlebox mode, the peer sends CCS messages. Set this parameter to allow receiving CCS messages */ ctx->method.ctrlCCS(ctx, CCS_CMD_RECV_READY); /* In middlebox mode, the server sends the CCS immediately after sending the hrr */ ctx->hsCtx->ccsNextState = TRY_RECV_CLIENT_HELLO; return HS_ChangeState(ctx, TRY_SEND_CHANGE_CIPHER_SPEC); } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/send/src/send_server_hello.c
C
unknown
14,646
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "hs_ctx.h" #include "hs_common.h" #include "hs_dtls_timer.h" #include "pack.h" #include "send_process.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t ServerSendServerHelloDoneProcess(TLS_Ctx *ctx) { int32_t ret; /* get the server infomation */ HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* determine whether to assemble a message */ if (hsCtx->msgLen == 0) { /* assemble message */ ret = HS_PackMsg(ctx, SERVER_HELLO_DONE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15879, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server pack server hello done msg fail.", 0, 0, 0, 0); return ret; } } /* writing Handshake message */ ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15880, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send server hello done msg success.", 0, 0, 0, 0); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) ret = HS_StartTimer(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ if (hsCtx->isNeedClientCert) { return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE); } return HS_ChangeState(ctx, TRY_RECV_CLIENT_KEY_EXCHANGE); } #endif /* #if HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/send/src/send_server_hello_done.c
C
unknown
2,248
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_HOST_SERVER #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 "hitls_crypt_type.h" #include "hitls_security.h" #include "tls.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "cert_method.h" #include "hs_ctx.h" #include "hs_common.h" #include "pack.h" #include "send_process.h" #include "alert.h" #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) #ifdef HITLS_TLS_SUITE_KX_DHE #define DEFAULT_DHE_PSK_BIT_NUM 112 #define TLS_DHE_PARAM_MAX_LEN 1024 #define DEFAULT_SECURITY_BITS 80 #define STRONG_CIPHER_STRENGTH_BITS 256 #define STRONG_DHE_SECURITY_BITS 128 #define IS_NOT_USE_CERTIFICATE_AUTH(cipherSuiteInfo) \ ((cipherSuiteInfo)->authAlg == HITLS_AUTH_NULL || (cipherSuiteInfo)->authAlg == HITLS_AUTH_PSK) #ifdef HITLS_TLS_CONFIG_MANUAL_DH static HITLS_CRYPT_Key *GenerateDhEphemeralKey(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CRYPT_Key *priKey) { uint8_t p[TLS_DHE_PARAM_MAX_LEN] = {0}; uint8_t g[TLS_DHE_PARAM_MAX_LEN] = {0}; uint16_t pLen = TLS_DHE_PARAM_MAX_LEN; uint16_t gLen = TLS_DHE_PARAM_MAX_LEN; int32_t ret = SAL_CRYPT_GetDhParameters(priKey, p, &pLen, g, &gLen); if (ret != HITLS_SUCCESS) { return NULL; } return SAL_CRYPT_GenerateDhKeyByParams(libCtx, attrName, p, pLen, g, gLen); } static HITLS_CRYPT_Key *GetDhKeyByDhTmp(TLS_Ctx *ctx) { HITLS_CRYPT_Key *key = NULL; HITLS_CRYPT_Key *dhParam = NULL; key = ctx->config.tlsConfig.dhTmp; if ((key == NULL) && (ctx->config.tlsConfig.dhTmpCb != NULL)) { dhParam = ctx->config.tlsConfig.dhTmpCb(ctx, 0, TLS_DHE_PARAM_MAX_LEN); key = dhParam; } if (key != NULL) { key = GenerateDhEphemeralKey(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), key); } SAL_CRYPT_FreeDhKey(dhParam); return key; } #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ static HITLS_CRYPT_Key *GetDhKeyBySecBits(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; int32_t secBits = DEFAULT_SECURITY_BITS; HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *certMgrCtx = config->certMgrCtx; CipherSuiteInfo *cipherSuiteInfo = &ctx->negotiatedInfo.cipherSuiteInfo; HITLS_CERT_X509 *cert = SAL_CERT_GetCurrentCert(certMgrCtx); if (IS_NOT_USE_CERTIFICATE_AUTH(cipherSuiteInfo)) { if (ctx->negotiatedInfo.cipherSuiteInfo.strengthBits == STRONG_CIPHER_STRENGTH_BITS) { secBits = STRONG_DHE_SECURITY_BITS; } } else if (cert != NULL) { HITLS_CERT_Key *pubkey = NULL; (void)SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_SECBITS, NULL, (void *)&secBits); SAL_CERT_KeyFree(certMgrCtx, pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17163, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GET_SECBITS fail", 0, 0, 0, 0); return NULL; } } else { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15113, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cert is null", 0, 0, 0, 0); return NULL; } int32_t securityLevelBits = #ifdef HITLS_TLS_FEATURE_SECURITY (SECURITY_GetSecbits(ctx->config.tlsConfig.securityLevel) != 0) ? SECURITY_GetSecbits(ctx->config.tlsConfig.securityLevel) : #endif /* HITLS_TLS_FEATURE_SECURITY */ DEFAULT_DHE_PSK_BIT_NUM; if (securityLevelBits > secBits) { secBits = securityLevelBits; } return SAL_CRYPT_GenerateDhKeyBySecbits(ctx, secBits); } static HITLS_CRYPT_Key *GetDhKey(TLS_Ctx *ctx) { HITLS_CRYPT_Key *key = NULL; HITLS_Config *config = &ctx->config.tlsConfig; #ifdef HITLS_TLS_CONFIG_MANUAL_DH if (!config->isSupportDhAuto) { key = GetDhKeyByDhTmp(ctx); } else #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ { key = GetDhKeyBySecBits(ctx); } if (key == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17161, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "key is null", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return NULL; } /* Temporary DH security check */ #ifdef HITLS_TLS_FEATURE_SECURITY int32_t secBits = 0; int32_t ret = SAL_CERT_KeyCtrl(config, key, CERT_KEY_CTRL_GET_SECBITS, NULL, (void *)&secBits); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17161, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GET_SECBITS fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); SAL_CRYPT_FreeDhKey(key); return NULL; } ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_TMP_DH, secBits, 0, key); if (ret != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17162, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SslCheck fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); SAL_CRYPT_FreeDhKey(key); return NULL; } #endif /* HITLS_TLS_FEATURE_SECURITY */ return key; } // Generate the DH cipher suite parameters static int32_t GenDhCipherSuiteParams(TLS_Ctx *ctx) { HITLS_CRYPT_Key *key = GetDhKey(ctx); if (key == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_GET_DH_KEY); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15744, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get dh key error when processing dh cipher suite.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_ERR_GET_DH_KEY; } uint8_t p[TLS_DHE_PARAM_MAX_LEN] = {0}; uint8_t g[TLS_DHE_PARAM_MAX_LEN] = {0}; uint16_t pLen = TLS_DHE_PARAM_MAX_LEN; uint16_t gLen = TLS_DHE_PARAM_MAX_LEN; /* Get p and g */ if (SAL_CRYPT_GetDhParameters(key, p, &pLen, g, &gLen) != HITLS_SUCCESS) { SAL_CRYPT_FreeDhKey(key); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_GET_DH_PARAMETERS); return RETURN_ALERT_PROCESS(ctx, HITLS_MSG_HANDLE_ERR_GET_DH_PARAMETERS, BINLOG_ID15745, "get dh parameters error", ALERT_INTERNAL_ERROR); } BSL_SAL_FREE(ctx->hsCtx->kxCtx->keyExchParam.dh.p); ctx->hsCtx->kxCtx->keyExchParam.dh.p = BSL_SAL_Dump(p, pLen); if (ctx->hsCtx->kxCtx->keyExchParam.dh.p == NULL) { SAL_CRYPT_FreeDhKey(key); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_GET_DH_PARAMETERS); return RETURN_ALERT_PROCESS(ctx, HITLS_MSG_HANDLE_ERR_GET_DH_PARAMETERS, BINLOG_ID16209, "BSL_SAL_Dump dh.p error", ALERT_INTERNAL_ERROR); } BSL_SAL_FREE(ctx->hsCtx->kxCtx->keyExchParam.dh.g); ctx->hsCtx->kxCtx->keyExchParam.dh.g = BSL_SAL_Dump(g, gLen); if (ctx->hsCtx->kxCtx->keyExchParam.dh.g == NULL) { BSL_SAL_FREE(ctx->hsCtx->kxCtx->keyExchParam.dh.p); SAL_CRYPT_FreeDhKey(key); BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_ERR_GET_DH_PARAMETERS); return RETURN_ALERT_PROCESS(ctx, HITLS_MSG_HANDLE_ERR_GET_DH_PARAMETERS, BINLOG_ID16210, "BSL_SAL_Dump dh.g error", ALERT_INTERNAL_ERROR); } ctx->hsCtx->kxCtx->keyExchParam.dh.plen = pLen; ctx->hsCtx->kxCtx->keyExchParam.dh.glen = gLen; ctx->hsCtx->kxCtx->key = key; return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_KX_DHE */ static int32_t PackExchMsgPrepare(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HITLS_CRYPT_Key *key = NULL; (void)ret; (void)key; switch (ctx->hsCtx->kxCtx->keyExchAlgo) { #ifdef HITLS_TLS_SUITE_KX_ECDHE case HITLS_KEY_EXCH_ECDHE: /* TLCP is included here. */ case HITLS_KEY_EXCH_ECDHE_PSK: key = SAL_CRYPT_GenEcdhKeyPair(ctx, &ctx->hsCtx->kxCtx->keyExchParam.ecdh.curveParams); if (key == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15746, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server generate ecdhe key pair error.", 0, 0, 0, 0); return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } ctx->hsCtx->kxCtx->key = key; break; #endif /* HITLS_TLS_SUITE_KX_ECDHE */ #ifdef HITLS_TLS_SUITE_KX_DHE case HITLS_KEY_EXCH_DHE: case HITLS_KEY_EXCH_DHE_PSK: ret = GenDhCipherSuiteParams(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15747, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "server generate dh key params error.", 0, 0, 0, 0); return ret; } break; #endif /* HITLS_TLS_SUITE_KX_DHE */ case HITLS_KEY_EXCH_PSK: case HITLS_KEY_EXCH_RSA_PSK: #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_KEY_EXCH_ECC: #endif break; default: BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15748, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unsupport kx algorithm when send server kx msg.", 0, 0, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_KX_ALG; } return HITLS_SUCCESS; } int32_t ServerSendServerKeyExchangeProcess(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; /* Determine whether the message needs to be packed */ if (hsCtx->msgLen == 0) { ret = PackExchMsgPrepare(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15948, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Fail to PackExchMsgPrepare, ret = %d.", ret, 0, 0, 0); return ret; } ret = HS_PackMsg(ctx, SERVER_KEY_EXCHANGE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15749, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Fail to pack Server Key Exchange Message, HS_PackMsg ret = %d", ret, 0, 0, 0); return ret; } } ret = HS_SendMsg(ctx); if (ret != HITLS_SUCCESS) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15750, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "server send keyExchange msg success.", 0, 0, 0, 0); /* Update the state machine. If the CertificateRequest message does not need to be sent, the system directly * switches to theSend_SERVER_HELLO_DONE state */ if (ctx->negotiatedInfo.cipherSuiteInfo.authAlg != HITLS_AUTH_NULL && ctx->negotiatedInfo.cipherSuiteInfo.authAlg != HITLS_AUTH_PSK && (ctx->config.tlsConfig.isSupportClientVerify == true) && (SAL_CERT_GetCurrentCert(ctx->config.tlsConfig.certMgrCtx) != NULL)) { if (ctx->negotiatedInfo.certReqSendTime < 1 || !(ctx->config.tlsConfig.isSupportClientOnceVerify)) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_REQUEST); } } /* Make sure the client will always send a certificate message, because ECDHE relies on the client's encrypted * certificate, even if the client does not require authentication (isSupportClientVerify equals false). */ #ifdef HITLS_TLS_PROTO_TLCP11 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11 && ctx->negotiatedInfo.cipherSuiteInfo.kxAlg == HITLS_KEY_EXCH_ECDHE) { return HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_REQUEST); } #endif return HS_ChangeState(ctx, TRY_SEND_SERVER_HELLO_DONE); } #endif /* HITLS_TLS_PROTO_TLS_BASIC || HITLS_TLS_PROTO_DTLS12 */ #endif /* HITLS_TLS_HOST_SERVER */
2301_79861745/bench_create
tls/handshake/send/src/send_server_key_exchange.c
C
unknown
12,125
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "hitls_error.h" #include "hitls_sni.h" #include "bsl_err_internal.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif /* HITLS_TLS_FEATURE_INDICATOR */ #include "hs_reass.h" #include "hs_common.h" #include "hs_verify.h" #include "hs_kx.h" #include "hs.h" #include "parse.h" #define DTLS_OVER_UDP_DEFAULT_SIZE 2048u #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) #define EXTRA_DATA_SIZE 128u #endif #ifdef HITLS_TLS_FEATURE_FLIGHT static int32_t UIO_Init(TLS_Ctx *ctx) { if (ctx->bUio != NULL) { return HITLS_SUCCESS; } int32_t ret = HITLS_SUCCESS; BSL_UIO *bUio = BSL_UIO_New(BSL_UIO_BufferMethod()); if (bUio == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17172, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "UIO_New fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) 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(bUio, BSL_UIO_SET_BUFFER_SIZE, sizeof(uint32_t), &bufferLen); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17173, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "SET_BUFFER_SIZE fail, ret %d", ret, 0, 0, 0); BSL_UIO_Free(bUio); BSL_ERR_PUSH_ERROR(HITLS_UIO_FAIL); return HITLS_UIO_FAIL; } } #endif ctx->bUio = bUio; ret = BSL_UIO_Append(bUio, ctx->uio); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17174, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "UIO_Append fail, ret %d", ret, 0, 0, 0); BSL_UIO_Free(bUio); ctx->bUio = NULL; return ret; } ctx->uio = bUio; return HITLS_SUCCESS; } static int32_t UIO_Deinit(TLS_Ctx *ctx) { if (ctx->bUio == NULL) { return HITLS_SUCCESS; } ctx->uio = BSL_UIO_PopCurrent(ctx->uio); BSL_UIO_FreeChain(ctx->bUio); ctx->bUio = NULL; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_FLIGHT */ static int32_t HsInitChangeState(TLS_Ctx *ctx) { if (ctx->isClient) { return HS_ChangeState(ctx, TRY_SEND_CLIENT_HELLO); } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION // the server sends a hello request first during renegotiation if (ctx->negotiatedInfo.isRenegotiation) { return HS_ChangeState(ctx, TRY_SEND_HELLO_REQUEST); } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ return HS_ChangeState(ctx, TRY_RECV_CLIENT_HELLO); } int32_t NewHsCtxConfig(TLS_Ctx *ctx, HS_Ctx *hsCtx) { (void)ctx; if (VERIFY_Init(hsCtx) != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17178, "VERIFY_Init fail"); } #ifdef HITLS_TLS_FEATURE_FLIGHT if (ctx->config.tlsConfig.isFlightTransmitEnable == true && UIO_Init(ctx) != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17179, "UIO_Init fail"); } #endif /* HITLS_TLS_FEATURE_FLIGHT */ hsCtx->kxCtx = HS_KeyExchCtxNew(); if (hsCtx->kxCtx == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17180, "KeyExchCtxNew fail"); } #ifdef HITLS_TLS_PROTO_TLS13 hsCtx->firstClientHello = NULL; #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_PROTO_DTLS12 hsCtx->reassMsg = HS_ReassNew(); if (hsCtx->reassMsg == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17181, "ReassNew fail"); } #endif #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_StatusIndicate(ctx, INDICATE_EVENT_HANDSHAKE_START, INDICATE_VALUE_SUCCESS); #endif /* HITLS_TLS_FEATURE_INDICATOR */ return HITLS_SUCCESS; } int32_t HS_Init(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; if (ctx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID17175, "ctx null"); } // prevent multiple init in the ctx->hsCtx if (ctx->hsCtx != NULL) { return HITLS_SUCCESS; } HS_Ctx *hsCtx = (HS_Ctx *)BSL_SAL_Calloc(1u, sizeof(HS_Ctx)); if (hsCtx == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17176, "Calloc fail"); } ctx->hsCtx = hsCtx; hsCtx->clientRandom = ctx->negotiatedInfo.clientRandom; hsCtx->serverRandom = ctx->negotiatedInfo.serverRandom; hsCtx->bufferLen = HITLS_HS_INIT_BUFFER_SIZE; hsCtx->msgBuf = BSL_SAL_Malloc(hsCtx->bufferLen); if (hsCtx->msgBuf == NULL) { (void)RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17177, "Malloc fail"); goto ERR; } ret = NewHsCtxConfig(ctx, hsCtx); if (ret != HITLS_SUCCESS) { goto ERR; } return HsInitChangeState(ctx); ERR: HS_DeInit(ctx); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } void HS_DeInit(TLS_Ctx *ctx) { if (ctx == NULL || ctx->hsCtx == NULL) { return; } HS_Ctx *hsCtx = ctx->hsCtx; HS_CleanMsg(ctx->hsCtx->hsMsg); BSL_SAL_FREE(ctx->hsCtx->hsMsg); BSL_SAL_FREE(hsCtx->msgBuf); #if defined(HITLS_TLS_FEATURE_SESSION) || defined(HITLS_TLS_PROTO_TLS13) BSL_SAL_FREE(hsCtx->sessionId); #endif /* HITLS_TLS_FEATURE_SESSION || HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_FEATURE_SNI BSL_SAL_FREE(hsCtx->serverName); #endif /* HITLS_TLS_FEATURE_SNI */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET BSL_SAL_FREE(hsCtx->ticket); #endif /* HITLS_TLS_FEATURE_SESSION_TICKET */ #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->hsCtx->firstClientHello != NULL) { HS_Msg hsMsg = {0}; hsMsg.type = CLIENT_HELLO; hsMsg.body.clientHello = *ctx->hsCtx->firstClientHello; HS_CleanMsg(&hsMsg); BSL_SAL_FREE(ctx->hsCtx->firstClientHello); } #endif /* HITLS_TLS_PROTO_TLS13 */ /* clear sensitive information */ BSL_SAL_CleanseData(hsCtx->masterKey, MAX_DIGEST_SIZE); if (hsCtx->peerCert != NULL) { SAL_CERT_PairFree(ctx->config.tlsConfig.certMgrCtx, hsCtx->peerCert); hsCtx->peerCert = NULL; } VERIFY_Deinit(hsCtx); #ifdef HITLS_TLS_FEATURE_FLIGHT if (ctx->config.tlsConfig.isFlightTransmitEnable == true) { UIO_Deinit(ctx); } #endif /* HITLS_TLS_FEATURE_FLIGHT */ HS_KeyExchCtxFree(hsCtx->kxCtx); #ifdef HITLS_TLS_PROTO_DTLS12 HS_ReassFree(hsCtx->reassMsg); #endif BSL_SAL_FREE(ctx->hsCtx); return; }
2301_79861745/bench_create
tls/handshake/sm/src/hs_init.c
C
unknown
7,160