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_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; *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 */
2302_82127028/openHiTLS-examples_1508
tls/handshake/parse/src/parse_extensions_client.c
C
unknown
17,359
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "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 */
2302_82127028/openHiTLS-examples_1508
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; }
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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); }
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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" #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) /** * @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; if (legacyVersion > HITLS_VERSION_TLS13 && !IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { legacyVersion = HITLS_VERSION_TLS12; } /* Check whether DTLS is used */ if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && !IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask)) { if (legacyVersion > ctx->config.tlsConfig.minVersion) { /** The DTLS version supported by the client is too early and the negotiation cannot be continued */ if (TLS_IS_FIRST_HANDSHAKE(ctx)) { ctx->negotiatedInfo.version = legacyVersion; } BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15223, 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; } /** Continue the version negotiation and obtain the earlier DTLS version between the latest versions of the * client and server */ if (legacyVersion < ctx->config.tlsConfig.maxVersion) { ctx->negotiatedInfo.version = ctx->config.tlsConfig.maxVersion; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15224, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "client want a unsupported protocol version 0x%02x.", legacyVersion, 0, 0, 0); } else { ctx->negotiatedInfo.version = legacyVersion; } } else { if (legacyVersion < ctx->config.tlsConfig.minVersion) { if (TLS_IS_FIRST_HANDSHAKE(ctx)) { ctx->negotiatedInfo.version = legacyVersion; } /* The TLS version supported by the client is too early and cannot be negotiated */ BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15225, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "client version = 0x%02x, min version = 0x%02x.", legacyVersion, ctx->config.tlsConfig.minVersion, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } /* Continue the version negotiation. Obtain the earlier version between the latest versions of the client and * server */ if (legacyVersion > ctx->config.tlsConfig.maxVersion) { ctx->negotiatedInfo.version = ctx->config.tlsConfig.maxVersion; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15226, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "client version = 0x%02x, max version = 0x%02x.", legacyVersion, ctx->config.tlsConfig.maxVersion, 0, 0); } else { ctx->negotiatedInfo.version = legacyVersion; } } #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 CheckVersion(TLS_Ctx *ctx, uint16_t version, uint16_t minVersion, uint16_t maxVersion, uint16_t *selectVersion) { if (version >= HITLS_VERSION_TLS13 && !IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { version = HITLS_VERSION_TLS12; } #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 */ (minVersion <= version) && (version <= maxVersion)) { *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 minVersion, uint16_t maxVersion, 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 = CheckVersion(ctx, version, minVersion, maxVersion, 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; } /* Find the supported version in the extended field supportedVersions. */ for (version = maxVersion; version >= minVersion; version--) { for (int i = 0; i < clientHello->extension.content.supportedVersionsCount; i++) { if (clientHello->extension.content.supportedVersions[i] != version) { continue; } if (((version == HITLS_VERSION_TLS13) && (!IsTls13KeyExchAvailable(ctx))) || (version <= HITLS_VERSION_SSL30)) { /* 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; TLS_Config *tlsConfig = &ctx->config.tlsConfig; 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, tlsConfig->minVersion, tlsConfig->maxVersion, &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 */
2302_82127028/openHiTLS-examples_1508
tls/handshake/recv/src/recv_client_hello.c
C
unknown
98,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 "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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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; }
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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); }
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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; }
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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) */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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 */
2302_82127028/openHiTLS-examples_1508
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; }
2302_82127028/openHiTLS-examples_1508
tls/handshake/sm/src/hs_init.c
C
unknown
7,160
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls.h" #include "rec.h" #include "tls.h" #include "hs.h" #include "hs_ctx.h" #include "hs_common.h" #include "parse.h" #include "hs_state_recv.h" #include "hs_state_send.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 "transcript_hash.h" #include "recv_process.h" #include "hs_dtls_timer.h" static int32_t HandshakeDone(TLS_Ctx *ctx) { (void)ctx; int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_FLIGHT /* If isFlightTransmitEnable is enabled, the server CCS and Finish information stored in the bUio must be sent after * the handshake is complete */ if (ctx->config.tlsConfig.isFlightTransmitEnable) { ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_FLUSH, 0, NULL); if (ret == BSL_UIO_IO_BUSY) { return HITLS_REC_NORMAL_IO_BUSY; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16109, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "fail to send the CCS and Finish message of server in bUio.", 0, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } } #endif /* HITLS_TLS_FEATURE_FLIGHT */ #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { return HITLS_SUCCESS; } bool isBuffEmpty = false; ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_SCTP_SND_BUFF_IS_EMPTY, sizeof(isBuffEmpty), &isBuffEmpty); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17188, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "SCTP_SND_BUFF_IS_EMPTY fail, ret %d", ret, 0, 0, 0); return HITLS_UIO_SCTP_IS_SND_BUF_EMPTY_FAIL; } if (isBuffEmpty != true) { return HITLS_REC_NORMAL_IO_BUSY; } // This branch is entered only when the hello request is just sent. if (!ctx->negotiatedInfo.isRenegotiation && ctx->userRenego) { return HITLS_SUCCESS; } ret = HS_ActiveSctpAuthKey(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_DeletePreviousSctpAuthKey(ctx); #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_SCTP */ return ret; } bool IsHsSendState(HITLS_HandshakeState state) { switch (state) { case TRY_SEND_HELLO_REQUEST: case TRY_SEND_CLIENT_HELLO: case TRY_SEND_HELLO_RETRY_REQUEST: case TRY_SEND_SERVER_HELLO: case TRY_SEND_HELLO_VERIFY_REQUEST: case TRY_SEND_ENCRYPTED_EXTENSIONS: case TRY_SEND_CERTIFICATE: case TRY_SEND_SERVER_KEY_EXCHANGE: case TRY_SEND_CERTIFICATE_REQUEST: case TRY_SEND_SERVER_HELLO_DONE: case TRY_SEND_CLIENT_KEY_EXCHANGE: case TRY_SEND_CERTIFICATE_VERIFY: case TRY_SEND_NEW_SESSION_TICKET: case TRY_SEND_CHANGE_CIPHER_SPEC: case TRY_SEND_END_OF_EARLY_DATA: case TRY_SEND_FINISH: case TRY_SEND_KEY_UPDATE: return true; default: break; } return false; } static bool IsHsRecvState(HITLS_HandshakeState state) { switch (state) { case TRY_RECV_CLIENT_HELLO: case TRY_RECV_SERVER_HELLO: case TRY_RECV_HELLO_VERIFY_REQUEST: case TRY_RECV_ENCRYPTED_EXTENSIONS: case TRY_RECV_CERTIFICATE: case TRY_RECV_SERVER_KEY_EXCHANGE: case TRY_RECV_CERTIFICATE_REQUEST: case TRY_RECV_SERVER_HELLO_DONE: case TRY_RECV_CLIENT_KEY_EXCHANGE: case TRY_RECV_CERTIFICATE_VERIFY: case TRY_RECV_NEW_SESSION_TICKET: case TRY_RECV_END_OF_EARLY_DATA: case TRY_RECV_FINISH: case TRY_RECV_KEY_UPDATE: case TRY_RECV_HELLO_REQUEST: return true; default: break; } return false; } int32_t HS_DoHandshake(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; HS_Ctx *hsCtx = ctx->hsCtx; #ifdef HITLS_TLS_FEATURE_INDICATOR int32_t eventType = (ctx->isClient) ? INDICATE_EVENT_STATE_CONNECT_EXIT : INDICATE_EVENT_STATE_ACCEPT_EXIT; #endif /* HITLS_TLS_FEATURE_INDICATOR */ while (hsCtx->state != TLS_CONNECTED) { if (IsHsSendState(hsCtx->state)) { ret = HS_SendMsgProcess(ctx); } else if (IsHsRecvState(hsCtx->state)) { ret = HS_RecvMsgProcess(ctx); } else { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_STATE_ILLEGAL); BSL_LOG_BINLOG_VARLEN(BINLOG_ID15884, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Handshake state unable to process, current state is %s.", HS_GetStateStr(hsCtx->state)); ret = HITLS_MSG_HANDLE_STATE_ILLEGAL; } if (ret != HITLS_SUCCESS) { #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_StatusIndicate(ctx, eventType, ret); #endif /* HITLS_TLS_FEATURE_INDICATOR */ return ret; } } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_StatusIndicate(ctx, INDICATE_EVENT_HANDSHAKE_DONE, INDICATE_VALUE_SUCCESS); #endif /* HITLS_TLS_FEATURE_INDICATOR */ ret = HandshakeDone(ctx); if (ret != HITLS_SUCCESS) { #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_StatusIndicate(ctx, eventType, ret); #endif /* HITLS_TLS_FEATURE_INDICATOR */ return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_StatusIndicate(ctx, eventType, INDICATE_VALUE_SUCCESS); #endif /* HITLS_TLS_FEATURE_INDICATOR */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_KEY_UPDATE int32_t HS_CheckKeyUpdateState(TLS_Ctx *ctx, uint32_t updateType) { if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { return HITLS_MSG_HANDLE_UNSUPPORT_VERSION; } if (ctx->state != CM_STATE_TRANSPORTING) { return HITLS_MSG_HANDLE_STATE_ILLEGAL; } if (updateType != HITLS_UPDATE_REQUESTED && updateType != HITLS_UPDATE_NOT_REQUESTED) { return HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_KEY_UPDATE */ #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HS_CheckAndProcess2MslTimeout(TLS_Ctx *ctx) { /* In non-UDP scenarios, the 2MSL timer timeout does not need to be checked */ if ((ctx->hsCtx == NULL) || !BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } bool isTimeout = false; int32_t ret = HS_IsTimeout(ctx, &isTimeout); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17189, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HS_IsTimeout fail", 0, 0, 0, 0); return ret; } /* If the retransmission queue times out, the retransmission queue is cleared and the hsCtx memory is released */ if (isTimeout) { REC_RetransmitListClean(ctx->recCtx); HS_DeInit(ctx); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ #ifdef HITLS_TLS_FEATURE_PHA int32_t HS_CheckPostHandshakeAuth(TLS_Ctx *ctx) { int32_t ret = HS_Init(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17190, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CONN_Init fail", 0, 0, 0, 0); return ret; } HS_ChangeState(ctx, TRY_SEND_CERTIFICATE_REQUEST); SAL_CRYPT_DigestFree(ctx->hsCtx->verifyCtx->hashCtx); ctx->hsCtx->verifyCtx->hashCtx = SAL_CRYPT_DigestCopy(ctx->phaHash); if (ctx->hsCtx->verifyCtx->hashCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_DIGEST); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16179, 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; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_PHA */
2302_82127028/openHiTLS-examples_1508
tls/handshake/sm/src/hs_sm.c
C
unknown
8,586
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 ALPN_H #define ALPN_H #include <stdint.h> #include "hitls_build.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif int32_t ALPN_SelectProtocol(uint8_t **out, uint32_t *outLen, uint8_t *clientAlpnList, uint32_t clientAlpnListLen, uint8_t *servAlpnList, uint32_t servAlpnListLen); int32_t ClientCheckNegotiatedAlpn( TLS_Ctx *ctx, bool haveSelectedAlpn, uint8_t *alpnSelected, uint16_t alpnSelectedSize); #ifdef __cplusplus } #endif #endif // ALPN_H
2302_82127028/openHiTLS-examples_1508
tls/include/alpn.h
C
unknown
1,019
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CIPHER_SUITE_H #define CIPHER_SUITE_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "hitls_config.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00ffu /* renegotiation cipher suite */ #define TLS_FALLBACK_SCSV 0x5600u /* downgraded protocol cipher suite */ /* cert request Type of the certificate requested */ typedef enum { /* rfc5246 7.4.4 */ CERT_TYPE_RSA_SIGN = 1, CERT_TYPE_DSS_SIGN = 2, CERT_TYPE_RSA_FIXED_DH = 3, CERT_TYPE_DSS_FIXED_DH = 4, /* rfc8422 5.5 */ CERT_TYPE_ECDSA_SIGN = 64, CERT_TYPE_UNKNOWN = 255 } CERT_Type; /** * CipherSuiteInfo structure, used to transfer public cipher suite information. */ typedef struct TlsCipherSuiteInfo { bool enable; /**< Enable flag */ const char *name; /**< Cipher suite name */ const char *stdName; /**< RFC name of the cipher suite */ uint16_t cipherSuite; /**< cipher suite */ /* algorithm type */ HITLS_CipherAlgo cipherAlg; /**< Symmetric-key algorithm */ HITLS_KeyExchAlgo kxAlg; /**< key exchange algorithm */ HITLS_AuthAlgo authAlg; /**< server authorization algorithm */ HITLS_MacAlgo macAlg; /**< mac algorithm */ HITLS_HashAlgo hashAlg; /**< hash algorithm */ /** * Signature combination, including the hash algorithm and signature algorithm: * TLS 1.2 negotiates the signScheme. */ HITLS_SignHashAlgo signScheme; /* key length */ uint8_t fixedIvLength; /**< If the AEAD algorithm is used, the value is the implicit IV length */ uint8_t encKeyLen; /**< Length of the symmetric key */ uint8_t macKeyLen; /**< If the AEAD algorithm is used, the MAC key length is 0 */ /* result length */ uint8_t blockLength; /**< If the block length is not zero, the alignment should be handled */ uint8_t recordIvLength; /**< The explicit IV needs to be sent to the peer end */ uint8_t macLen; /**< The length of the MAC address. If the AEAD algorithm is used, this member variable * will be the length of the tag */ uint16_t minVersion; /**< Minimum version supported by the cipher suite */ uint16_t maxVersion; /**< Maximum version supported by the cipher suite */ uint16_t minDtlsVersion; /**< Minimum DTLS version supported by the cipher suite */ uint16_t maxDtlsVersion; /**< Maximum DTLS version supported by the cipher suite */ HITLS_CipherType cipherType; /**< Encryption algorithm type */ int32_t strengthBits; /**< Encryption algorithm strength */ } CipherSuiteInfo; /** * SignSchemeInfo structure, used to transfer the signature algorithm information. */ typedef struct { HITLS_SignHashAlgo scheme; /**< Signature hash algorithm */ HITLS_SignAlgo signAlg; /**< Signature algorithm */ HITLS_HashAlgo hashAlg; /**< hash algorithm */ } SignSchemeInfo; typedef struct { HITLS_SignHashAlgo scheme; /**< signature algorithm */ HITLS_NamedGroup cureName; /**< public key curve name (ECDSA only) */ } EcdsaCurveInfo; /** * Mapping between cipher suites and certificate types */ typedef struct { uint16_t cipherSuite; /**< cipher suite */ CERT_Type certType; /**< Certificate type */ } CipherSuiteCertType; /** * @brief Obtain the cipher suite information. * * @param cipherSuite [IN] Cipher suite of the information to be obtained * @param cipherInfo [OUT] Cipher suite information * * @retval HITLS_SUCCESS obtained successfully. * @retval HITLS_INTERNAL_EXCEPTION An unexpected internal error. * @retval HITLS_MEMCPY_FAIL memcpy_s failed to be executed. * @retval HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE No information about the cipher suite is found. */ int32_t CFG_GetCipherSuiteInfo(uint16_t cipherSuite, CipherSuiteInfo *cipherInfo); /** * @brief Check whether the input cipher suite is supported. * * @param cipherSuite [IN] cipher suite to be checked * * @retval true Supported * @retval false Not supported */ bool CFG_CheckCipherSuiteSupported(uint16_t cipherSuite); /** * @brief Check whether the input cipher suite complies with the version. * * @param cipherSuite [IN] cipher suite to be checked * @param minVersion [IN] Indicates the earliest version of the cipher suite. * @param maxVersion [IN] Indicates the latest version of the cipher suite. * * @retval true Supported * @retval false Not supported */ bool CFG_CheckCipherSuiteVersion(uint16_t cipherSuite, uint16_t minVersion, uint16_t maxVersion); /** * @brief Obtain the signature algorithm and hash algorithm by combining the parameters of * the signature hash algorithm. * @param ctx [IN] TLS context * @param scheme [IN] Signature and hash algorithm combination * @param signAlg [OUT] Signature algorithm * @param hashAlg [OUT] Hash algorithm * * @retval true Obtained successfully. * @retval false Obtaining failed. */ bool CFG_GetSignParamBySchemes(const HITLS_Ctx *ctx, HITLS_SignHashAlgo scheme, HITLS_SignAlgo *signAlg, HITLS_HashAlgo *hashAlg); /** * @brief Obtain the certificate type based on the cipher suite. * * @param cipherSuite [IN] Cipher suite * * @retval Certificate type corresponding to the cipher suite */ uint8_t CFG_GetCertTypeByCipherSuite(uint16_t cipherSuite); /** * @brief get the group name of the ecdsa * * @param scheme [IN] signature algorithm * * @retval group name */ HITLS_NamedGroup CFG_GetEcdsaCurveNameBySchemes(const HITLS_Ctx *ctx, HITLS_SignHashAlgo scheme); #ifdef __cplusplus } #endif #endif // CIPHER_SUITE_H
2302_82127028/openHiTLS-examples_1508
tls/include/cipher_suite.h
C
unknown
6,459
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CUSTOM_EXTENSIONS_H #define CUSTOM_EXTENSIONS_H #include "hitls_build.h" #include "hitls.h" #include "hitls_custom_extensions.h" #include "tls.h" #define MAX_LIMIT_CUSTOM_EXT 20 // Define CustomExtMethod structure typedef struct { uint16_t extType; uint32_t context; HITLS_AddCustomExtCallback addCb; HITLS_FreeCustomExtCallback freeCb; void *addArg; HITLS_ParseCustomExtCallback parseCb; void *parseArg; } CustomExtMethod; // Define CustomExtMethods structure typedef struct CustomExtMethods { CustomExtMethod *meths; uint32_t methsCount; } CustomExtMethods; /** * @brief Determines if packing custom extensions is needed for a given context. * * This function checks whether there are any custom extensions that need to be packed * based on the provided context. It iterates through the list of custom extension methods * and evaluates if any of them match the specified context. * * @param exts [IN] Pointer to the CustomExtMethods structure containing extension methods * @param context [IN] The context to check against the custom extensions * @retval true if there are custom extensions that need to be packed for the given context * @retval false otherwise */ bool IsPackNeedCustomExtensions(CustomExtMethods *exts, uint32_t context); /** * @brief Determines if parsing custom extensions is needed for a given extension type and context. * * This function checks whether there are any custom extensions that need to be parsed * based on the provided extension type and context. It iterates through the list of custom * extension methods and evaluates if any of them match the specified extension type and context. * * @param exts [IN] Pointer to the CustomExtMethods structure containing extension methods * @param extType [IN] The extension type to check against the custom extensions * @param context [IN] The context to check against the custom extensions * @retval true if there are custom extensions that need to be parsed for the given extension type and context * @retval false otherwise */ bool IsParseNeedCustomExtensions(CustomExtMethods *exts, uint16_t extType, uint32_t context); /** * @brief Packs custom extensions into the provided buffer for a given context. * * This function iterates through the list of custom extension methods associated with the TLS context * and packs the relevant custom extensions into the provided buffer. It checks each extension method * to determine if it should be included based on the specified context. If an extension is applicable, * it uses the associated add callback to pack the extension data into the buffer. * * @param ctx [IN] Pointer to the TLS context containing custom extension methods * @param pkt [IN/OUT] Context for packing * @param context [IN] The context to check against the custom extensions * @param cert [IN] Pointer to the HITLS_CERT_X509 structure representing certificate information * @param certIndex [IN] Certificate index indicating its position in the certificate chain * @retval HITLS_SUCCESS if the custom extensions are successfully packed * @retval An error code if packing fails, see hitls_error.h for details */ int32_t PackCustomExtensions(const struct TlsCtx *ctx, PackPacket *pkt, uint32_t context, HITLS_CERT_X509 *cert, uint32_t certIndex); /** * @brief Frees the custom extension methods in the HITLS configuration. * * This function frees the custom extension methods in the HITLS configuration. * * @param exts [IN] Pointer to the CustomExtMethods structure containing extension methods */ void FreeCustomExtensions(CustomExtMethods *exts); /** * @brief Duplicates the custom extension methods in the HITLS configuration. * * This function duplicates the custom extension methods in the HITLS configuration. * * @param exts [IN] Pointer to the CustomExtMethods structure containing extension methods * @retval Pointer to the duplicated CustomExtMethods structure */ CustomExtMethods *DupCustomExtensions(CustomExtMethods *exts); /** * @brief Parses custom extensions from the provided buffer for a given extension type and context. * * This function iterates through the list of custom extension methods associated with the TLS context * and parses the relevant custom extensions from the provided buffer. It checks each extension method * to determine if it should be parsed based on the specified extension type and context. If an extension * is applicable, it uses the associated parse callback to interpret the extension data. * * @param ctx [IN] Pointer to the TLS context containing custom extension methods * @param buf [IN] Buffer containing the custom extensions to be parsed * @param extType [IN] The extension type to check against the custom extensions * @param extLen [IN] Length of the extension data in the buffer * @param context [IN] The context to check against the custom extensions * @param cert [IN] Pointer to the HITLS_CERT_X509 structure representing certificate information * @param certIndex [IN] Certificate index indicating its position in the certificate chain * @retval HITLS_SUCCESS if the custom extensions are successfully parsed * @retval An error code if parsing fails, see hitls_error.h for details */ int32_t ParseCustomExtensions(const struct TlsCtx *ctx, const uint8_t *buf, uint16_t extType, uint32_t extLen, uint32_t context, HITLS_CERT_X509 *cert, uint32_t certIndex); #endif // CUSTOM_EXTENSIONS_H
2302_82127028/openHiTLS-examples_1508
tls/include/custom_extensions.h
C
unknown
6,119
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_cert_reg * @ingroup hitls * @brief Certificate related interfaces to be registered */ #ifndef HITLS_CERT_REG_H #define HITLS_CERT_REG_H #include <stdint.h> #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup hitls_cert_reg * @brief Create a certificate store * * @param void * * @retval Certificate store */ typedef HITLS_CERT_Store *(*CERT_StoreNewCallBack)(void); /** * @ingroup hitls_cert_reg * @brief Duplicate the certificate store. * * @param store [IN] Certificate store. * * @retval New certificate store. */ typedef HITLS_CERT_Store *(*CERT_StoreDupCallBack)(HITLS_CERT_Store *store); /** * @ingroup hitls_cert_reg * @brief Release the certificate store. * * @param store [IN] Certificate store. * * @retval void */ typedef void (*CERT_StoreFreeCallBack)(HITLS_CERT_Store *store); /** * @ingroup hitls_cert_reg * @brief ctrl interface * * @param config [IN] TLS link configuration. * @param store [IN] Certificate store. * @param cmd [IN] Ctrl option. * @param input [IN] Input. * @param output [IN] Output. * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_StoreCtrlCallBack)(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_CtrlCmd cmd, void *input, void *output); /** * @ingroup hitls_cert_reg * @brief Create a certificate chain based on the device certificate in use. * * @attention If the function is successful, the certificate in the certificate chain is managed by the HiTLS, * and the user does not need to release the memory. Otherwise, the certificate chain is an empty pointer * array. * @param config [IN] TLS link configuration * @param store [IN] Certificate store * @param cert [IN] Device certificate * @param certList [OUT] Certificate chain, which is a pointer array. Each element indicates a certificate. * The first element is the device certificate. * @param num [IN/OUT] IN: maximum length of the certificate chain OUT: length of the certificate chain * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_BuildCertChainCallBack)(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_X509 *cert, HITLS_CERT_X509 **certList, uint32_t *num); /** * @ingroup hitls_cert_reg * @brief Verify the certificate chain * * @param ctx [IN] TLS link object * @param store [IN] Certificate store. * @param certList [IN] Certificate chain, a pointer array, each element indicates a certificate. * The first element indicates the device certificate. * @param num [IN] Certificate chain length. * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_VerifyCertChainCallBack)(HITLS_Ctx *ctx, HITLS_CERT_Store *store, HITLS_CERT_X509 **certList, uint32_t num); /** * @ingroup hitls_cert_reg * @brief Encode the certificate in ASN.1 DER format. * * @param ctx [IN] TLS link object. * @param cert [IN] Certificate. * @param buf [OUT] Certificate encoding data. * @param len [IN] Maximum encoding length. * @param usedLen [OUT] Actual encoding length. * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_CertEncodeCallBack)(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, uint8_t *buf, uint32_t len, uint32_t *usedLen); /** * @ingroup hitls_cert_reg * @brief Read the certificate. * * @attention If the data is loaded to config, config points to the TLS configuration. * If the data is loaded to the TLS object, the config command is used only for a single link. * * @param config [IN] TLS link configuration, which can be used to obtain the passwd callback. * @param buf [IN] Certificate data. * @param len [IN] Certificate data length. * @param type [IN] Parsing type. * @param format [IN] Data format. * * @retval Certificate */ typedef HITLS_CERT_X509 *(*CERT_CertParseCallBack)(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); /** * @ingroup hitls_cert_reg * @brief Duplicate the certificate. * * @param cert [IN] Certificate * * @retval New certificate */ typedef HITLS_CERT_X509 *(*CERT_CertDupCallBack)(HITLS_CERT_X509 *cert); /** * @ingroup hitls_cert_reg * @brief Certificate reference counting plus one. * * @param cert [IN] Certificate * * @retval certificate */ typedef HITLS_CERT_X509 *(*CERT_CertRefCallBack)(HITLS_CERT_X509 *cert); /** * @ingroup hitls_cert_reg * @brief Release the certificate. * * @param cert [IN] Certificate * * @retval void */ typedef void (*CERT_CertFreeCallBack)(HITLS_CERT_X509 *cert); /** * @ingroup hitls_cert_reg * @brief Ctrl interface * * @param config [IN] TLS link configuration * @param cert [IN] Certificate * @param cmd [IN] Ctrl option * @param input [IN] Input * @param output [IN] Output * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_CertCtrlCallBack)(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_CtrlCmd cmd, void *input, void *output); /** * @ingroup hitls_cert_reg * @brief Read the certificate key. * @attention If the data is loaded to config, config points to the TLS configuration. * If the data is loaded to the TLS object, the config command applies only to a single link. * * @param config [IN] LTS link configuration, which can be used to obtain the passwd callback. * @param buf [IN] Private key data * @param len [IN] Data length * @param type [IN] Parsing type * @param format [IN] Data format * * @retval Certificate key */ typedef HITLS_CERT_Key *(*CERT_KeyParseCallBack)(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); /** * @ingroup hitls_cert_reg * @brief Duplicate the certificate key. * * @param key [IN] Certificate key * * @retval New certificate key */ typedef HITLS_CERT_Key *(*CERT_KeyDupCallBack)(HITLS_CERT_Key *key); /** * @ingroup hitls_cert_reg * @brief Release the certificate key. * * @param key [IN] Certificate key * * @retval void */ typedef void (*CERT_KeyFreeCallBack)(HITLS_CERT_Key *key); /** * @ingroup hitls_cert_reg * @brief Ctrl interface * * @param config [IN] TLS link configuration. * @param key [IN] Certificate key. * @param cmd [IN] Ctrl option. * @param input [IN] Input. * @param output [IN] Output. * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_KeyCtrlCallBack)(HITLS_Config *config, HITLS_CERT_Key *key, HITLS_CERT_CtrlCmd cmd, void *input, void *output); /** * @ingroup hitls_cert_reg * @brief Signature * * @param ctx [IN] TLS link object * @param key [IN] Certificate private key * @param signAlgo [IN] Signature algorithm * @param hashAlgo [IN] Hash algorithm * @param data [IN] Data to be signed * @param dataLen [IN] Data length * @param sign [OUT] Signature * @param signLen [IN/OUT] IN: maximum signature length OUT: actual signature length * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_CreateSignCallBack)(HITLS_Ctx *ctx, HITLS_CERT_Key *key, HITLS_SignAlgo signAlgo, HITLS_HashAlgo hashAlgo, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen); /** * @ingroup hitls_cert_reg * @brief Signature verification * * @param ctx [IN] TLS link object * @param key [IN] Certificate public key * @param signAlgo [IN] Signature algorithm * @param hashAlgo [IN] Hash algorithm * @param data [IN] Data to be signed * @param dataLen [IN] Data length * @param sign [IN] Signature * @param signLen [IN] Signature length * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_VerifySignCallBack)(HITLS_Ctx *ctx, HITLS_CERT_Key *key, HITLS_SignAlgo signAlgo, HITLS_HashAlgo hashAlgo, const uint8_t *data, uint32_t dataLen, const uint8_t *sign, uint32_t signLen); /** * @ingroup hitls_cert_reg * @brief Encrypted by the certificate public key. * * @param ctx [IN] TLS link object. * @param key [IN] Certificate public key. * @param in [IN] Plaintext. * @param inLen [IN] Plaintext length. * @param out [OUT] Ciphertext. * @param outLen [IN/OUT] IN: maximum ciphertext length OUT: actual ciphertext length. * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_EncryptCallBack)(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @ingroup hitls_cert_reg * @brief Use the certificate private key to decrypt the data. * * @param ctx [IN] TLS link object. * @param key [IN] Certificate private key. * @param in [IN] Ciphertext. * @param inLen [IN] Ciphertext length. * @param out [OUT] Plaintext. * @param outLen [IN/OUT] IN: maximum plaintext length OUT: actual plaintext length. * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_DecryptCallBack)(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @ingroup hitls_cert_reg * @brief Check whether the private key matches the certificate. * * @param config [IN] TLS link configuration. * @param cert [IN] Certificate. * @param key [IN] Private key. * * @retval HITLS_SUCCESS indicates success. Other values are considered as failure. */ typedef int32_t (*CERT_CheckPrivateKeyCallBack)(const HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_Key *key); typedef struct { CERT_StoreNewCallBack certStoreNew; /**< REQUIRED, Creating a certificate store. */ CERT_StoreDupCallBack certStoreDup; /**< REQUIRED, duplicate certificate store. */ CERT_StoreFreeCallBack certStoreFree; /**< REQUIRED, release the certificate store. */ CERT_StoreCtrlCallBack certStoreCtrl; /**< REQUIRED, certificate interface store ctrl. */ CERT_BuildCertChainCallBack buildCertChain; /**< REQUIRED, construct a certificate chain. */ CERT_VerifyCertChainCallBack verifyCertChain; /**< REQUIRED, verify certificate chain. */ CERT_CertEncodeCallBack certEncode; /**< REQUIRED, certificate encode. */ CERT_CertParseCallBack certParse; /**< REQUIRED, certificate decoding. */ CERT_CertDupCallBack certDup; /**< REQUIRED, duplicate the certificate. */ CERT_CertRefCallBack certRef; /**< OPTIONAL, Certificate reference counting plus one. */ CERT_CertFreeCallBack certFree; /**< REQUIRED, release certificate. */ CERT_CertCtrlCallBack certCtrl; /**< REQUIRED, certificate interface ctrl. */ CERT_KeyParseCallBack keyParse; /**< REQUIRED, loading key. */ CERT_KeyDupCallBack keyDup; /**< REQUIRED, duplicate key. */ CERT_KeyFreeCallBack keyFree; /**< REQUIRED, Release the key. */ CERT_KeyCtrlCallBack keyCtrl; /**< REQUIRED, key ctrl interface. */ CERT_CreateSignCallBack createSign; /**< REQUIRED, signature. */ CERT_VerifySignCallBack verifySign; /**< REQUIRED, verification. */ CERT_EncryptCallBack encrypt; /**< OPTIONAL, RSA key exchange REQUIRED, RSA encryption. */ CERT_DecryptCallBack decrypt; /**< OPTIONAL, RSA key exchange REQUIRED, RSA decryption. */ CERT_CheckPrivateKeyCallBack checkPrivateKey; /**< REQUIRED, Check whether the certificate matches the key. */ } HITLS_CERT_MgrMethod; /** * @ingroup hitls_cert_reg * @brief Callback function related to certificate registration * * @param method [IN] Callback function * * @retval HITLS_SUCCESS, succeeded. * @retval HITLS_NULL_INPUT, the callback function is NULL. */ int32_t HITLS_CERT_RegisterMgrMethod(HITLS_CERT_MgrMethod *method); /** * @ingroup hitls_cert_reg * @brief Certificate deregistration callback function * * @param method [IN] Callback function * * @retval */ void HITLS_CERT_DeinitMgrMethod(void); /** * @ingroup hitls_cert_reg * @brief Register the private key with the config file and certificate matching Check Interface. * * @param config [IN/OUT] Config context * @param checkPrivateKey API registration * @retval HITLS_SUCCESS. * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_SetCheckPriKeyCb(HITLS_Config *config, CERT_CheckPrivateKeyCallBack checkPrivateKey); /** * @ingroup hitls_cert_reg * @brief Interface for obtaining the registered private key and certificate matching check * * @param config [IN] Config context * * @retval The interface for checking whether the registered private key matches the certificate is returned. * If the registered private key does not match the certificate, NULL is returned. */ CERT_CheckPrivateKeyCallBack HITLS_CFG_GetCheckPriKeyCb(HITLS_Config *config); /** * @ingroup hitls_cert_reg * @brief Get certificate callback function * * @retval Cert callback function */ HITLS_CERT_MgrMethod *HITLS_CERT_GetMgrMethod(void); #ifdef __cplusplus } #endif #endif /* HITLS_CERT_REG_H */
2302_82127028/openHiTLS-examples_1508
tls/include/hitls_cert_reg.h
C
unknown
14,277
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /** * @defgroup hitls_crypt_reg * @ingroup hitls * @brief Algorithm related interfaces to be registered */ #ifndef HITLS_CRYPT_REG_H #define HITLS_CRYPT_REG_H #include <stdint.h> #include "hitls_type.h" #include "hitls_crypt_type.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Input parameters for KEM encapsulation */ typedef struct { HITLS_NamedGroup groupId; /**< Named group ID */ uint8_t *peerPubkey; /**< Peer's public key */ uint32_t pubKeyLen; /**< Length of peer's public key */ uint8_t *ciphertext; /**< [OUT] Encapsulated ciphertext */ uint32_t *ciphertextLen; /**< [IN/OUT] IN: Maximum ciphertext buffer length OUT: Actual ciphertext length */ uint8_t *sharedSecret; /**< [OUT] Generated shared secret */ uint32_t *sharedSecretLen; /**< [IN/OUT] IN: Maximum shared secret buffer length OUT: Actual shared secret length */ } HITLS_KemEncapsulateParams; /** * @ingroup hitls_crypt_reg * @brief Obtain the random number. * * @param buf [OUT] Random number * @param len [IN] Random number length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_RandBytesCallback)(uint8_t *buf, uint32_t len); /** * @ingroup hitls_crypt_reg * @brief ECDH: Generate a key pair based on elliptic curve parameters. * * @param curveParams [IN] Elliptic curve parameter * * @retval Key handle */ typedef HITLS_CRYPT_Key *(*CRYPT_GenerateEcdhKeyPairCallback)(const HITLS_ECParameters *curveParams); /** * @ingroup hitls_crypt_reg * @brief Release the key. * * @param key [IN] Key handle */ typedef void (*CRYPT_FreeEcdhKeyCallback)(HITLS_CRYPT_Key *key); /** * @ingroup hitls_crypt_reg * @brief ECDH: Extract the public key data. * * @param key [IN] Key handle * @param pubKeyBuf [OUT] Public key data * @param bufLen [IN] Buffer length * @param pubKeyLen [OUT] Public key data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_GetEcdhEncodedPubKeyCallback)(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *pubKeyLen); /** * @ingroup hitls_crypt_reg * @brief ECDH: Calculate the shared key based on the local key and peer public key. Ref RFC 8446 section 7.4.1, * this callback should strip the leading zeros. * * @param key [IN] Key handle * @param peerPubkey [IN] Public key data * @param pubKeyLen [IN] Public key data length * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of the key padding OUT: Key length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_CalcEcdhSharedSecretCallback)(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen); /** * @ingroup hitls_crypt_reg * @brief KEM: Encapsulate a shared secret using peer's public key. * * @param params [IN/OUT] Parameters for KEM encapsulation * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_KemEncapsulateCallback)(HITLS_KemEncapsulateParams *params); /** * @ingroup hitls_crypt_reg * @brief KEM: Decapsulate the ciphertext to recover shared secret. * * @param key [IN] Key handle * @param ciphertext [IN] Ciphertext buffer * @param ciphertextLen [IN] Ciphertext length * @param sharedSecret [OUT] Shared secret buffer * @param sharedSecretLen [IN/OUT] IN: Maximum length of the shared secret buffer OUT: Actual shared secret length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_KemDecapsulateCallback)(HITLS_CRYPT_Key *key, const uint8_t *ciphertext, uint32_t ciphertextLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen); /** * @ingroup hitls_crypt_reg * @brief SM2 calculates the shared key based on the local key and peer public key. * * @param sm2Params [IN] Shared key calculation parameters * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of the key padding OUT: Key length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_Sm2CalcEcdhSharedSecretCallback)(HITLS_Sm2GenShareKeyParameters *sm2Params, uint8_t *sharedSecret, uint32_t *sharedSecretLen); /** * @ingroup hitls_crypt_reg * @brief Generate a key pair based on secbits. * * @param secbits [IN] Key security level * * @retval Key handle */ typedef HITLS_CRYPT_Key *(*CRYPT_GenerateDhKeyBySecbitsCallback)(int32_t secbits); /** * @ingroup hitls_crypt_reg * @brief DH: Generate a key pair based on the dh parameter. * * @param p [IN] p Parameter * @param plen [IN] p Parameter length * @param g [IN] g Parameter * @param glen [IN] g Parameter length * * @retval Key handle */ typedef HITLS_CRYPT_Key *(*CRYPT_GenerateDhKeyByParamsCallback)(uint8_t *p, uint16_t plen, uint8_t *g, uint16_t glen); /** * @ingroup hitls_crypt_reg * @brief Deep copy key * * @param key [IN] Key handle * @retval Key handle */ typedef HITLS_CRYPT_Key *(*CRYPT_DupDhKeyCallback)(HITLS_CRYPT_Key *key); /** * @ingroup hitls_crypt_reg * @brief Release the key. * * @param key [IN] Key handle */ typedef void (*CRYPT_FreeDhKeyCallback)(HITLS_CRYPT_Key *key); /** * @ingroup hitls_crypt_reg * @brief DH: Obtain p g plen glen by using the key handle. * * @attention If the p and g parameters are null pointers, only the lengths of p and g are obtained. * * @param key [IN] Key handle * @param p [OUT] p Parameter * @param plen [IN/OUT] IN: Maximum length of data padding OUT: p Parameter length * @param g [OUT] g Parameter * @param glen [IN/OUT] IN: Maximum length of data padding OUT: g Parameter length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_DHGetParametersCallback)(HITLS_CRYPT_Key *key, uint8_t *p, uint16_t *plen, uint8_t *g, uint16_t *glen); /** * @ingroup hitls_crypt_reg * @brief DH: Extract the Dh public key data. * * @param key [IN] Key handle * @param pubKeyBuf [OUT] Public key data * @param bufLen [IN] Buffer length * @param pubKeyLen [OUT] Public key data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_GetDhEncodedPubKeyCallback)(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *pubKeyLen); /** * @ingroup hitls_crypt_reg * @brief DH: Calculate the shared key based on the local key and peer public key. Ref RFC 5246 section 8.1.2, * this callback should retain the leading zeros. * * @param key [IN] Key handle * @param peerPubkey [IN] Public key data * @param pubKeyLen [IN] Public key data length * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of the key padding OUT: Key length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_CalcDhSharedSecretCallback)(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen); /** * @ingroup hitls_crypt_reg * @brief Obtain the HMAC length based on the hash algorithm. * * @param hashAlgo [IN] Hash algorithm * * @retval HMAC length */ typedef uint32_t (*CRYPT_HmacSizeCallback)(HITLS_HashAlgo hashAlgo); /** * @ingroup hitls_crypt_reg * @brief Initialize the HMAC context. * * @param hashAlgo [IN] Hash algorithm * @param key [IN] Key * @param len [IN] Key length * * @retval HMAC context */ typedef HITLS_HMAC_Ctx *(*CRYPT_HmacInitCallback)(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t len); /** * @ingroup hitls_crypt_reg * @brief reinit the HMAC context. * * @param ctx [IN] HMAC context * * @retval HMAC context */ typedef int32_t (*CRYPT_HmacReInitCallback)(HITLS_HMAC_Ctx *ctx); /** * @ingroup hitls_crypt_reg * @brief Release the HMAC context. * * @param ctx [IN] HMAC context */ typedef void (*CRYPT_HmacFreeCallback)(HITLS_HMAC_Ctx *ctx); /** * @ingroup hitls_crypt_reg * @brief Add the HMAC input data. * * @param ctx [IN] HMAC context * @param data [IN] Input data * @param len [IN] Data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_HmacUpdateCallback)(HITLS_HMAC_Ctx *ctx, const uint8_t *data, uint32_t len); /** * @ingroup hitls_crypt_reg * @brief Output the HMAC result. * * @param ctx [IN] HMAC context * @param out [OUT] Output data * @param len [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_HmacFinalCallback)(HITLS_HMAC_Ctx *ctx, uint8_t *out, uint32_t *len); /** * @ingroup hitls_crypt_reg * @brief Function for calculating the HMAC for a single time * * @param hashAlgo [IN] Hash algorithm * @param key [IN] Key * @param keyLen [IN] Key length * @param in [IN] Input data. * @param inLen [IN] Input data length * @param out [OUT] Output the HMAC data result. * @param outLen [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_HmacCallback)(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t keyLen, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @ingroup hitls_crypt_reg * @brief Obtain the hash length. * * @param hashAlgo [IN] Hash algorithm. * * @retval Hash length */ typedef uint32_t (*CRYPT_DigestSizeCallback)(HITLS_HashAlgo hashAlgo); /** * @ingroup hitls_crypt_reg * @brief Initialize the hash context. * * @param hashAlgo [IN] Hash algorithm * * @retval Hash context */ typedef HITLS_HASH_Ctx *(*CRYPT_DigestInitCallback)(HITLS_HashAlgo hashAlgo); /** * @ingroup hitls_crypt_reg * @brief Copy the hash context. * * @param ctx [IN] Hash Context * * @retval Hash context */ typedef HITLS_HASH_Ctx *(*CRYPT_DigestCopyCallback)(HITLS_HASH_Ctx *ctx); /** * @ingroup hitls_crypt_reg * @brief Release the hash context. * * @param ctx [IN] Hash Context */ typedef void (*CRYPT_DigestFreeCallback)(HITLS_HASH_Ctx *ctx); /** * @ingroup hitls_crypt_reg * @brief Hash Add input data. * * @param ctx [IN] Hash context * @param data [IN] Input data * @param len [IN] Input data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_DigestUpdateCallback)(HITLS_HASH_Ctx *ctx, const uint8_t *data, uint32_t len); /** * @ingroup hitls_crypt_reg * @brief Output the hash result. * * @param ctx [IN] Hash context * @param out [IN] Output data. * @param len [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_DigestFinalCallback)(HITLS_HASH_Ctx *ctx, uint8_t *out, uint32_t *len); /** * @ingroup hitls_crypt_reg * @brief Hash function * * @param hashAlgo [IN] Hash algorithm * @param in [IN] Input data * @param inLen [IN] Input data length * @param out [OUT] Output data * @param outLen [IN/OUT] IN: Maximum buffer length OUT: Output data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_DigestCallback)(HITLS_HashAlgo hashAlgo, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @ingroup hitls_crypt_reg * @brief TLS encryption * * Provides the encryption capability for records, including the AEAD and CBC algorithms. * Encrypts the input factor (key parameter) and plaintext based on the record protocol * to obtain the ciphertext. * * @attention: The protocol allows the sending of app packets with payload length 0. * Therefore, the length of the plaintext input may be 0. Therefore, * the plaintext with the length of 0 must be encrypted. * @param cipher [IN] Key parameters * @param in [IN] Plaintext data * @param inLen [IN] Plaintext data length * @param out [OUT] Ciphertext data * @param outLen [IN/OUT] IN: maximum buffer length OUT: ciphertext data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_EncryptCallback)(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @ingroup hitls_crypt_reg * @brief TLS decryption * * Provides decryption capabilities for records, including the AEAD and CBC algorithms. * Decrypt the input factor (key parameter) and ciphertext according to the record protocol to obtain the plaintext. * * @param cipher [IN] Key parameters * @param in [IN] Ciphertext data * @param inLen [IN] Ciphertext data length * @param out [OUT] Plaintext data * @param outLen [IN/OUT] IN: maximum buffer length OUT: plaintext data length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_DecryptCallback)(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @ingroup hitls_crypt_reg * @brief Release the cipher ctx. * * @param ctx [IN] cipher ctx handle */ typedef void (*CRYPT_CipherFreeCallback)(HITLS_Cipher_Ctx *ctx); /** * @ingroup hitls_crypt_reg * @brief HKDF-Extract * * @param input [IN] Enter the key material. * @param prk [OUT] Output key * @param prkLen [IN/OUT] IN: Maximum buffer length OUT: Output key length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_HkdfExtractCallback)(const HITLS_CRYPT_HkdfExtractInput *input, uint8_t *prk, uint32_t *prkLen); /** * @ingroup hitls_crypt_reg * @brief HKDF-Expand * * @param input [IN] Enter the key material. * @param outputKeyMaterial [OUT] Output key * @param outputKeyMaterialLen [IN] Output key length * * @retval 0 indicates success. Other values indicate failure. */ typedef int32_t (*CRYPT_HkdfExpandCallback)( const HITLS_CRYPT_HkdfExpandInput *input, uint8_t *outputKeyMaterial, uint32_t outputKeyMaterialLen); /** * @ingroup hitls_cert_reg * @brief Callback function that must be registered */ typedef struct { CRYPT_RandBytesCallback randBytes; /**< Obtain the random number. */ CRYPT_HmacSizeCallback hmacSize; /**< HMAC: obtain the HMAC length based on the hash algorithm. */ CRYPT_HmacInitCallback hmacInit; /**< HMAC: initialize the context. */ CRYPT_HmacReInitCallback hmacReinit; /**< HMAC: reinitialize the context. */ CRYPT_HmacFreeCallback hmacFree; /**< HMAC: release the context. */ CRYPT_HmacUpdateCallback hmacUpdate; /**< HMAC: add input data. */ CRYPT_HmacFinalCallback hmacFinal; /**< HMAC: output result. */ CRYPT_HmacCallback hmac; /**< HMAC: single HMAC function. */ CRYPT_DigestSizeCallback digestSize; /**< HASH: obtains the hash length. */ CRYPT_DigestInitCallback digestInit; /**< HASH: initialize the context. */ CRYPT_DigestCopyCallback digestCopy; /**< HASH: copy the hash context. */ CRYPT_DigestFreeCallback digestFree; /**< HASH: release the context. */ CRYPT_DigestUpdateCallback digestUpdate; /**< HASH: add input data. */ CRYPT_DigestFinalCallback digestFinal; /**< HASH: output the hash result. */ CRYPT_DigestCallback digest; /**< HASH: single hash function. */ CRYPT_EncryptCallback encrypt; /**< TLS encryption: provides the encryption capability for records. */ CRYPT_DecryptCallback decrypt; /**< TLS decryption: provides the decryption capability for records. */ CRYPT_CipherFreeCallback cipherFree; /**< CIPHER: release the context. */ } HITLS_CRYPT_BaseMethod; /** * @ingroup hitls_cert_reg * @brief ECDH Callback function to be registered */ typedef struct { CRYPT_GenerateEcdhKeyPairCallback generateEcdhKeyPair; /**< ECDH: generate a key pair based on the elliptic curve parameters. */ CRYPT_FreeEcdhKeyCallback freeEcdhKey; /**< ECDH: release the elliptic curve key. */ CRYPT_GetEcdhEncodedPubKeyCallback getEcdhPubKey; /**< ECDH: extract public key data. */ CRYPT_CalcEcdhSharedSecretCallback calcEcdhSharedSecret; /**< ECDH: calculate the shared key based on the local key and peer public key. */ CRYPT_Sm2CalcEcdhSharedSecretCallback sm2CalEcdhSharedSecret; CRYPT_KemEncapsulateCallback kemEncapsulate; /**< KEM: encapsulate a shared secret */ CRYPT_KemDecapsulateCallback kemDecapsulate; /**< KEM: decapsulate the ciphertext */ } HITLS_CRYPT_EcdhMethod; /** * @ingroup hitls_cert_reg * @brief DH Callback function to be registered */ typedef struct { CRYPT_GenerateDhKeyBySecbitsCallback generateDhKeyBySecbits; /**< DH: Generate a key pair based on secbits */ CRYPT_GenerateDhKeyByParamsCallback generateDhKeyByParams; /**< DH: Generate a key pair based on the dh parameter */ CRYPT_DupDhKeyCallback dupDhKey; /**< DH: deep copy key*/ CRYPT_FreeDhKeyCallback freeDhKey; /**< DH: release the key */ CRYPT_DHGetParametersCallback getDhParameters; /**< DH: obtain the p g plen glen by using the key handle */ CRYPT_GetDhEncodedPubKeyCallback getDhPubKey; /**< DH: extract the Dh public key data */ CRYPT_CalcDhSharedSecretCallback calcDhSharedSecret; /**< DH: calculate the shared key based on the local key and peer public key */ } HITLS_CRYPT_DhMethod; /** * @ingroup hitls_cert_reg * @brief KDF function */ typedef struct { CRYPT_HkdfExtractCallback hkdfExtract; CRYPT_HkdfExpandCallback hkdfExpand; } HITLS_CRYPT_KdfMethod; /** * @ingroup hitls_cert_reg * @brief Register the basic callback function. * * @param userCryptCallBack [IN] Callback function to be registered * * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter is NULL.. */ int32_t HITLS_CRYPT_RegisterBaseMethod(HITLS_CRYPT_BaseMethod *userCryptCallBack); /** * @ingroup hitls_cert_reg * @brief Register the ECDH callback function. * * @param userCryptCallBack [IN] Callback function to be registered * * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter is NULL.. */ int32_t HITLS_CRYPT_RegisterEcdhMethod(HITLS_CRYPT_EcdhMethod *userCryptCallBack); /** * @ingroup hitls_cert_reg * @brief Register the callback function of the DH. * * @param userCryptCallBack [IN] Callback function to be registered * * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter is NULL.. */ int32_t HITLS_CRYPT_RegisterDhMethod(const HITLS_CRYPT_DhMethod *userCryptCallBack); /** * @brief Register the callback function of the HKDF. * * @param userCryptCallBack [IN] Callback function to be registered * * @retval HITLS_SUCCESS, if successful. * @retval HITLS_NULL_INPUT, the input parameter is NULL.. */ int32_t HITLS_CRYPT_RegisterHkdfMethod(HITLS_CRYPT_KdfMethod *userCryptCallBack); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
tls/include/hitls_crypt_reg.h
C
unknown
20,718
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef INDICATOR_H #define INDICATOR_H #include "hitls_build.h" #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define INDICATOR_ALERT_LEVEL_OFFSET 8 #define INDICATE_INFO_STATE_MASK 0x0FFF // 0000 1111 1111 1111 /** * @ingroup indicator * @brief Indicate the status or event to the upper layer through the infoCb * @param ctx [IN] TLS context * @param eventType [IN] * @param value [IN] Return value of a function in the event or alert type */ void INDICATOR_StatusIndicate(const HITLS_Ctx *ctx, int32_t eventType, int32_t value); /** * @ingroup indicator * @brief Indicate the status or event to the upper layer through msgCb * @param writePoint [IN] Message direction in the callback ">>>" or "<<<" * @param tlsVersion [IN] TLS version * @param contentType[IN] Type of the message to be processed. * @param msg [IN] Internal message processing instruction data in callback * @param msgLen [IN] Data length of the processing instruction * @param ctx [IN] HITLS context * @param arg [IN] User data such as BIO */ void INDICATOR_MessageIndicate(int32_t writePoint, uint32_t tlsVersion, int32_t contentType, const void *msg, uint32_t msgLen, HITLS_Ctx *ctx, void *arg); #ifdef __cplusplus } #endif #endif // INDICATOR_H
2302_82127028/openHiTLS-examples_1508
tls/include/indicator.h
C
unknown
1,904
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef SECURITY_H #define SECURITY_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define SECURITY_SUCCESS 1 #define SECURITY_ERR 0 /* set the default security level and security callback function */ void SECURITY_SetDefault(HITLS_Config *config); /* check TLS configuration security */ int32_t SECURITY_CfgCheck(const HITLS_Config *config, int32_t option, int32_t bits, int32_t id, void *other); /* check TLS link security */ int32_t SECURITY_SslCheck(const HITLS_Ctx *ctx, int32_t option, int32_t bits, int32_t id, void *other); /* get the security strength corresponding to the security level */ int32_t SECURITY_GetSecbits(int32_t level); #ifdef __cplusplus } #endif #endif // SECURITY_H
2302_82127028/openHiTLS-examples_1508
tls/include/security.h
C
unknown
1,283
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef SESSION_H #define SESSION_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "sal_time.h" #include "hitls_session.h" #include "cert.h" #ifdef __cplusplus extern "C" { #endif #define MAX_MASTER_KEY_SIZE 256u /* <= tls1.2 master key is 48 bytes. TLS1.3 can be to 256 bytes. */ /* Increments the reference count for session */ void HITLS_SESS_UpRef(HITLS_Session *sess); /* Deep copy session */ HITLS_Session *SESS_Copy(HITLS_Session *src); /* Disable session */ void SESS_Disable(HITLS_Session *sess); /* set peerCert */ int32_t SESS_SetPeerCert(HITLS_Session *sess, CERT_Pair *peerCert, bool isClient); /* get peerCert */ int32_t SESS_GetPeerCert(HITLS_Session *sess, CERT_Pair **peerCert); /* set ticket */ int32_t SESS_SetTicket(HITLS_Session *sess, uint8_t *ticket, uint32_t ticketSize); /* get ticket */ int32_t SESS_GetTicket(const HITLS_Session *sess, uint8_t **ticket, uint32_t *ticketSize); /* set hostName */ int32_t SESS_SetHostName(HITLS_Session *sess, uint32_t hostNameSize, uint8_t *hostName); /* get hostName */ int32_t SESS_GetHostName(HITLS_Session *sess, uint32_t *hostNameSize, uint8_t **hostName); /* Check the validity of the session */ bool SESS_CheckValidity(HITLS_Session *sess, uint64_t curTime); uint64_t SESS_GetStartTime(HITLS_Session *sess); int32_t SESS_SetStartTime(HITLS_Session *sess, uint64_t startTime); int32_t SESS_SetTicketAgeAdd(HITLS_Session *sess, uint32_t ticketAgeAdd); uint32_t SESS_GetTicketAgeAdd(const HITLS_Session *sess); #ifdef __cplusplus } #endif #endif // SESSION_H
2302_82127028/openHiTLS-examples_1508
tls/include/session.h
C
unknown
2,121
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef SESSION_MGR_H #define SESSION_MGR_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "hitls.h" #include "tls.h" #include "session.h" #include "tls_config.h" #ifdef __cplusplus extern "C" { #endif /* Application */ TLS_SessionMgr *SESSMGR_New(HITLS_Lib_Ctx *libCtx); /* Copy the number of references and increase the number of references by 1 */ TLS_SessionMgr *SESSMGR_Dup(TLS_SessionMgr *mgr); /* Release */ void SESSMGR_Free(TLS_SessionMgr *mgr); /* Configure the timeout period */ void SESSMGR_SetTimeout(TLS_SessionMgr *mgr, uint64_t sessTimeout); /* Obtain the timeout configuration */ uint64_t SESSMGR_GetTimeout(TLS_SessionMgr *mgr); /* Set the mode */ void SESSMGR_SetCacheMode(TLS_SessionMgr *mgr, HITLS_SESS_CACHE_MODE mode); /* Set the mode: Ensure that the pointer is not null */ HITLS_SESS_CACHE_MODE SESSMGR_GetCacheMode(TLS_SessionMgr *mgr); /* Set the maximum number of cache sessions */ void SESSMGR_SetCacheSize(TLS_SessionMgr *mgr, uint32_t sessCacheSize); /* Set the maximum number of cached sessions. Ensure that the pointer is not null */ uint32_t SESSMGR_GetCacheSize(TLS_SessionMgr *mgr); /* add */ void SESSMGR_InsertSession(TLS_SessionMgr *mgr, HITLS_Session *sess, bool isClient); /* Find the matching session and verify the validity of the session (time) */ HITLS_Session *SESSMGR_Find(TLS_SessionMgr *mgr, uint8_t *sessionId, uint8_t sessionIdSize); /* Search for the matching session without checking the validity of the session (time) */ bool SESSMGR_HasMacthSessionId(TLS_SessionMgr *mgr, uint8_t *sessionId, uint8_t sessionIdSize); /* Clear timeout sessions */ void SESSMGR_ClearTimeout(TLS_SessionMgr *mgr); /* Generate session IDs to prevent duplicate session IDs */ int32_t SESSMGR_GernerateSessionId(TLS_Ctx *ctx, uint8_t *sessionId, uint32_t sessionIdSize); void SESSMGR_SetTicketKeyCb(TLS_SessionMgr *mgr, HITLS_TicketKeyCb ticketKeyCb); HITLS_TicketKeyCb SESSMGR_GetTicketKeyCb(TLS_SessionMgr *mgr); /** * @brief Obtain the default ticket key of the HITLS. The key is used to encrypt and decrypt the ticket * in the new session ticket when the HITLS_TicketKeyCb callback function is not set. * * @attention The returned key value is as follows: 16-bytes key name + 32-bytes AES key + 32-bytes HMAC key * * @param mgr [IN] Session management context * @param key [OUT] Obtained ticket key * @param keySize [IN] Size of the key array * @param outSize [OUT] Size of the obtained ticket key * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_GetTicketKey(const TLS_SessionMgr *mgr, uint8_t *key, uint32_t keySize, uint32_t *outSize); /** * @brief Set the default ticket key of the HITLS. The key is used to encrypt and decrypt tickets * in the new session ticket when the HITLS_TicketKeyCb callback function is not set. * * @attention The returned key value is as follows: 16-bytes key name + 32-bytes AES key + 32-bytes HMAC key * * @param mgr [OUT] Session management context * @param key [IN] Ticket key to be set * @param keySize [IN] Size of the ticket key * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_SetTicketKey(TLS_SessionMgr *mgr, const uint8_t *key, uint32_t keySize); /** * @brief Encrypt the session ticket, which is invoked when a new session ticket is sent * * @param sessMgr [IN] Session management context * @param sess [IN] sess structure, used to generate ticket data * @param ticketBuf [OUT] ticket. The return value may be empty, that is, an empty new session ticket message is sent * @param ticketBufSize [IN] Size of the ticketBuf * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_EncryptSessionTicket(TLS_Ctx *ctx, const TLS_SessionMgr *sessMgr, const HITLS_Session *sess, uint8_t **ticketBuf, uint32_t *ticketBufSize); /** * @brief Decrypt the session ticket. This interface is invoked when the session ticket of the clientHello is received * * @attention The output parameters are as follows: * If the sess field is empty and the ticketExcept field is set to true, the new session ticket message * is sent but the session is not resumed * If the sess field is empty and the ticketExcept field is false, the session is not resumed * and the new session ticket message is not sent * If sess is not empty and ticketExcept is true, the session is resumed and * a new session ticket message is sent, which means the session ticket is renewed * If sess is not empty and ticketExcept is false, * the session is resumed and the new session ticket message is not sent * * @param sessMgr [IN] Session management context * @param sess [OUT] Session structure generated by the ticket. The return value may be empty, * so that, the corresponding session cannot be generated and the session cannot be resumed * @param ticketBuf [IN] ticket data * @param ticketBufSize [IN] Ticket data size * @param isTicketExcept [OUT] Indicates whether to send a new session ticket. * The options are as follows: true: yes; false: no. * * @retval HITLS_SUCCESS * @retval For other error codes, see hitls_error.h */ int32_t SESSMGR_DecryptSessionTicket(HITLS_Lib_Ctx *libCtx, const char *attrName, const TLS_SessionMgr *sessMgr, HITLS_Session **sess, const uint8_t *ticketBuf, uint32_t ticketBufSize, bool *isTicketExcept); #ifdef __cplusplus } #endif #endif // SESSION_MGR_H
2302_82127028/openHiTLS-examples_1508
tls/include/session_mgr.h
C
unknown
6,194
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef SNI_H #define SNI_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct SniArg { char *serverName; int32_t alert; } SNI_Arg; /* compare whether the host names are the same */ int32_t SNI_StrcaseCmp(const char *s1, const char *s2); #ifdef __cplusplus } #endif #endif // ALPN_H
2302_82127028/openHiTLS-examples_1508
tls/include/sni.h
C
unknown
863
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef TLS_H #define TLS_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "cipher_suite.h" #include "tls_config.h" #include "hitls_error.h" #ifdef __cplusplus extern "C" { #endif #define MAX_DIGEST_SIZE 64UL /* The longest known value is SHA512 */ #define DTLS_DEFAULT_PMTU 1500uL /* RFC 6083 4.1. Mapping of DTLS Records: The supported maximum length of SCTP user messages MUST be at least 2^14 + 2048 + 13 = 18445 bytes (2^14 + 2048 is the maximum length of the DTLSCiphertext.fragment, and 13 is the size of the DTLS record header). */ #define DTLS_SCTP_PMTU 18445uL #define IS_DTLS_VERSION(version) (((version) & 0x8u) == 0x8u) #define IS_SUPPORT_STREAM(versionBits) (((versionBits) & STREAM_VERSION_BITS) != 0x0u) #define IS_SUPPORT_DATAGRAM(versionBits) (((versionBits) & DATAGRAM_VERSION_BITS) != 0x0u) #define IS_SUPPORT_TLCP(versionBits) (((versionBits) & TLCP_VERSION_BITS) != 0x0u) #define DTLS_COOKIE_LEN 255 #define MAC_KEY_LEN 32u /* the length of mac key */ #define UNPROCESSED_APP_MSG_COUNT_MAX 50 /* number of APP data cached */ #define RANDOM_SIZE 32u /* the size of random number */ typedef struct TlsCtx TLS_Ctx; typedef struct HsCtx HS_Ctx; typedef struct CcsCtx CCS_Ctx; typedef struct AlertCtx ALERT_Ctx; typedef struct RecCtx REC_Ctx; typedef enum { CCS_CMD_RECV_READY, /* CCS allowed to be received */ CCS_CMD_RECV_EXIT_READY, /* CCS cannot be received */ CCS_CMD_RECV_ACTIVE_CIPHER_SPEC, /* CCS active change cipher spec */ } CCS_Cmd; /* Check whether the CCS message is received */ typedef bool (*IsRecvCcsCallback)(const TLS_Ctx *ctx); /* Send a CCS message */ typedef int32_t (*SendCcsCallback)(TLS_Ctx *ctx); /* Control the CCS */ typedef int32_t (*CtrlCcsCallback)(TLS_Ctx *ctx, CCS_Cmd cmd); typedef enum { ALERT_LEVEL_WARNING = 1, ALERT_LEVEL_FATAL = 2, ALERT_LEVEL_UNKNOWN = 255, } ALERT_Level; typedef enum { ALERT_CLOSE_NOTIFY = 0, ALERT_UNEXPECTED_MESSAGE = 10, ALERT_BAD_RECORD_MAC = 20, ALERT_DECRYPTION_FAILED = 21, ALERT_RECORD_OVERFLOW = 22, ALERT_DECOMPRESSION_FAILURE = 30, ALERT_HANDSHAKE_FAILURE = 40, ALERT_NO_CERTIFICATE_RESERVED = 41, ALERT_BAD_CERTIFICATE = 42, ALERT_UNSUPPORTED_CERTIFICATE = 43, ALERT_CERTIFICATE_REVOKED = 44, ALERT_CERTIFICATE_EXPIRED = 45, ALERT_CERTIFICATE_UNKNOWN = 46, ALERT_ILLEGAL_PARAMETER = 47, ALERT_UNKNOWN_CA = 48, ALERT_ACCESS_DENIED = 49, ALERT_DECODE_ERROR = 50, ALERT_DECRYPT_ERROR = 51, ALERT_EXPORT_RESTRICTION_RESERVED = 60, ALERT_PROTOCOL_VERSION = 70, ALERT_INSUFFICIENT_SECURITY = 71, ALERT_INTERNAL_ERROR = 80, ALERT_INAPPROPRIATE_FALLBACK = 86, ALERT_USER_CANCELED = 90, ALERT_NO_RENEGOTIATION = 100, ALERT_MISSING_EXTENSION = 109, ALERT_UNSUPPORTED_EXTENSION = 110, ALERT_CERTIFICATE_UNOBTAINABLE = 111, ALERT_UNRECOGNIZED_NAME = 112, ALERT_BAD_CERTIFICATE_STATUS_RESPONSE = 113, ALERT_BAD_CERTIFICATE_HASH_VALUE = 114, ALERT_UNKNOWN_PSK_IDENTITY = 115, ALERT_CERTIFICATE_REQUIRED = 116, ALERT_NO_APPLICATION_PROTOCOL = 120, ALERT_UNKNOWN = 255 } ALERT_Description; /** Connection management state */ typedef enum { CM_STATE_IDLE, CM_STATE_HANDSHAKING, CM_STATE_TRANSPORTING, CM_STATE_RENEGOTIATION, CM_STATE_ALERTING, CM_STATE_ALERTED, CM_STATE_CLOSED, CM_STATE_END } CM_State; /** post-handshake auth */ typedef enum { PHA_NONE, /* not support pha */ PHA_EXTENSION, /* pha extension send or received */ PHA_PENDING, /* try to send certificate request */ PHA_REQUESTED /* certificate request has been sent or received */ } PHA_State; /* Describes the handshake status */ typedef enum { TLS_IDLE, /* initial state */ TLS_CONNECTED, /* Handshake succeeded */ TRY_SEND_HELLO_REQUEST, /* sends hello request message */ TRY_SEND_CLIENT_HELLO, /* sends client hello message */ TRY_SEND_HELLO_RETRY_REQUEST, /* sends hello retry request message */ TRY_SEND_SERVER_HELLO, /* sends server hello message */ TRY_SEND_HELLO_VERIFY_REQUEST, /* sends hello verify request message */ TRY_SEND_ENCRYPTED_EXTENSIONS, /* sends encrypted extensions message */ TRY_SEND_CERTIFICATE, /* sends certificate message */ TRY_SEND_SERVER_KEY_EXCHANGE, /* sends server key exchange message */ TRY_SEND_CERTIFICATE_REQUEST, /* sends certificate request message */ TRY_SEND_SERVER_HELLO_DONE, /* sends server hello done message */ TRY_SEND_CLIENT_KEY_EXCHANGE, /* sends client key exchange message */ TRY_SEND_CERTIFICATE_VERIFY, /* sends certificate verify message */ TRY_SEND_NEW_SESSION_TICKET, /* sends new session ticket message */ TRY_SEND_CHANGE_CIPHER_SPEC, /* sends change cipher spec message */ TRY_SEND_END_OF_EARLY_DATA, /* sends end of early data message */ TRY_SEND_FINISH, /* sends finished message */ TRY_SEND_KEY_UPDATE, /* sends keyupdate message */ TRY_RECV_CLIENT_HELLO, /* attempts to receive client hello message */ TRY_RECV_SERVER_HELLO, /* attempts to receive server hello message */ TRY_RECV_HELLO_VERIFY_REQUEST, /* attempts to receive hello verify request message */ TRY_RECV_ENCRYPTED_EXTENSIONS, /* attempts to receive encrypted extensions message */ TRY_RECV_CERTIFICATE, /* attempts to receive certificate message */ TRY_RECV_SERVER_KEY_EXCHANGE, /* attempts to receive server key exchange message */ TRY_RECV_CERTIFICATE_REQUEST, /* attempts to receive certificate request message */ TRY_RECV_SERVER_HELLO_DONE, /* attempts to receive server hello done message */ TRY_RECV_CLIENT_KEY_EXCHANGE, /* attempts to receive client key exchange message */ TRY_RECV_CERTIFICATE_VERIFY, /* attempts to receive certificate verify message */ TRY_RECV_NEW_SESSION_TICKET, /* attempts to receive new session ticket message */ TRY_RECV_END_OF_EARLY_DATA, /* attempts to receive end of early data message */ TRY_RECV_FINISH, /* attempts to receive finished message */ TRY_RECV_KEY_UPDATE, /* attempts to receive keyupdate message */ TRY_RECV_HELLO_REQUEST, /* attempts to receive hello request message */ HS_STATE_BUTT = 255 /* enumerated Maximum Value */ } HITLS_HandshakeState; typedef enum { TLS_PROCESS_STATE_A, TLS_PROCESS_STATE_B } HitlsProcessState; typedef void (*SendAlertCallback)(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description); typedef bool (*GetAlertFlagCallback)(const TLS_Ctx *ctx); typedef int32_t (*UnexpectMsgHandleCallback)(TLS_Ctx *ctx, uint32_t msgType, const uint8_t *data, uint32_t dataLen, bool isPlain); /** Connection management configure */ typedef struct TLSCtxConfig { void *userData; /* user data */ uint16_t linkMtu; /* Maximum transport unit of a path (bytes), including IP header and udp/tcp header */ uint16_t pmtu; /* Maximum transport unit of a path (bytes) */ bool isSupportPto; /* is support process based TLS offload */ uint8_t reserved[1]; /* four-byte alignment */ TLS_Config tlsConfig; /* tls configure context */ } TLS_CtxConfig; typedef struct { uint32_t algRemainTime; /* current key usage times */ uint8_t preMacKey[MAC_KEY_LEN]; /* previous random key */ uint8_t macKey[MAC_KEY_LEN]; /* random key used by the current algorithm */ } CookieInfo; typedef struct { uint16_t version; /* negotiated version */ uint16_t clientVersion; /* version field of client hello */ uint32_t cookieSize; /* cookie length */ uint8_t *cookie; /* cookie data */ CookieInfo cookieInfo; /* cookie info with calculation and verification */ CipherSuiteInfo cipherSuiteInfo; /* cipher suite info */ HITLS_SignHashAlgo signScheme; /* sign algorithm used by the local */ uint8_t *alpnSelected; /* alpn proto */ uint32_t alpnSelectedSize; uint8_t clientVerifyData[MAX_DIGEST_SIZE]; /* client verify data */ uint8_t serverVerifyData[MAX_DIGEST_SIZE]; /* server verify data */ uint8_t clientRandom[RANDOM_SIZE]; /* client random number */ uint8_t serverRandom[RANDOM_SIZE]; /* server random number */ uint32_t clientVerifyDataSize; /* client verify data size */ uint32_t serverVerifyDataSize; /* server verify data size */ uint32_t renegotiationNum; /* the number of renegotiation */ uint32_t certReqSendTime; /* certificate request sending times */ uint32_t tls13BasicKeyExMode; /* TLS13_KE_MODE_PSK_ONLY || TLS13_KE_MODE_PSK_WITH_DHE || TLS13_CERT_AUTH_WITH_DHE */ uint16_t negotiatedGroup; /* negotiated group */ uint16_t recordSizeLimit; /* read record size limit */ uint16_t renegoRecordSizeLimit; uint16_t peerRecordSizeLimit; /* write record size limit */ bool isResume; /* whether to resume the session */ bool isRenegotiation; /* whether to renegotiate */ bool isSecureRenegotiation; /* whether security renegotiation */ bool isExtendedMasterSecret; /* whether to calculate the extended master sercret */ bool isEncryptThenMac; /* Whether to enable EncryptThenMac */ bool isEncryptThenMacRead; /* Whether to enable EncryptThenMacRead */ bool isEncryptThenMacWrite; /* Whether to enable EncryptThenMacWrite */ bool isTicket; /* whether to negotiate tickets, only below tls1.3 */ bool isSniStateOK; /* Whether server successfully processes the server_name callback */ } TLS_NegotiatedInfo; typedef struct { uint16_t *groups; /* all groups sent by the peer end */ uint32_t groupsSize; /* size of a group */ uint16_t *cipherSuites; /* all cipher suites sent by the peer end */ uint16_t cipherSuitesSize; /* size of a cipher suites */ HITLS_SignHashAlgo peerSignHashAlg; /* peer signature algorithm */ uint16_t *signatureAlgorithms; uint16_t signatureAlgorithmsSize; HITLS_ERROR verifyResult; /* record the certificate verification result of the peer end */ HITLS_TrustedCAList *caList; /* peer trusted ca list */ } PeerInfo; struct TlsCtx { bool isClient; /* is Client */ bool userShutDown; /* record whether the local end invokes the HITLS_Close */ bool userRenego; /* record whether the local end initiates renegotiation */ uint8_t rwstate; /* record the current internal read and write state */ CM_State preState; CM_State state; uint32_t shutdownState; /* Record the shutdown state */ void *rUio; /* read uio */ void *uio; /* write uio */ void *bUio; /* Storing uio */ HS_Ctx *hsCtx; /* handshake context */ CCS_Ctx *ccsCtx; /* ChangeCipherSpec context */ ALERT_Ctx *alertCtx; /* alert context */ REC_Ctx *recCtx; /* record context */ struct { IsRecvCcsCallback isRecvCCS; SendCcsCallback sendCCS; /* send a CCS message */ CtrlCcsCallback ctrlCCS; /* controlling CCS */ SendAlertCallback sendAlert; /* set the alert message to be sent */ GetAlertFlagCallback getAlertFlag; /* get alert state */ UnexpectMsgHandleCallback unexpectedMsgProcessCb; /* the callback for unexpected messages */ } method; PeerInfo peerInfo; /* Temporarily save the messages sent by the peer end */ TLS_CtxConfig config; /* private configuration */ TLS_Config *globalConfig; /* global configuration */ TLS_NegotiatedInfo negotiatedInfo; /* TLS negotiation information */ HITLS_Session *session; /* session information */ uint8_t clientAppTrafficSecret[MAX_DIGEST_SIZE]; /* TLS1.3 client app traffic secret */ uint8_t serverAppTrafficSecret[MAX_DIGEST_SIZE]; /* TLS1.3 server app traffic secret */ uint8_t resumptionMasterSecret[MAX_DIGEST_SIZE]; /* TLS1.3 session resume secret */ uint32_t bytesLeftToRead; /* bytes left to read after hs header has parsed */ uint32_t keyUpdateType; /* TLS1.3 key update type */ bool isKeyUpdateRequest; /* TLS1.3 Check whether there are unsent key update messages */ bool haveClientPointFormats; /* whether the EC point format extension in the client hello is processed */ uint8_t peekFlag; /* peekFlag equals 0, read mode; otherwise, peek mode */ bool hasParsedHsMsgHeader; /* has parsed current hs msg header */ int32_t errorCode; /* Record the tls error code */ HITLS_HASH_Ctx *phaHash; /* tls1.3 pha: Handshake main process hash */ HITLS_HASH_Ctx *phaCurHash; /* tls1.3 pha: Temporarily store the current pha hash */ PHA_State phaState; /* tls1.3 pha state */ uint8_t *certificateReqCtx; /* tls1.3 pha certificate_request_context */ uint32_t certificateReqCtxSize; /* tls1.3 pha certificate_request_context */ bool isDtlsListen; bool plainAlertForbid; /* tls1.3 forbid to receive plain alert message */ bool allowAppOut; /* whether user used HITLS_read to start renegotiation */ bool noQueryMtu; /* Don't query the mtu from bio */ bool needQueryMtu; /* whether need query mtu from bio */ bool mtuModified; /* whether mtu has been modified */ }; typedef struct { uint8_t **buf; // &hsCtx->msgbuf uint32_t *bufLen; // &hsCtx->bufferLen uint32_t *bufOffset; // &hsCtx->msgLen } PackPacket; #define LIBCTX_FROM_CTX(ctx) ((ctx == NULL) ? NULL : (ctx)->config.tlsConfig.libCtx) #define ATTRIBUTE_FROM_CTX(ctx) ((ctx == NULL) ? NULL : (ctx)->config.tlsConfig.attrName) #define CUSTOM_EXT_FROM_CTX(ctx) ((ctx == NULL) ? NULL : (ctx)->config.tlsConfig.customExts) #ifdef __cplusplus } #endif #endif /* TLS_H */
2302_82127028/openHiTLS-examples_1508
tls/include/tls.h
C
unknown
15,877
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef TLS_BINLOG_ID_H #define TLS_BINLOG_ID_H #include <stdint.h> #include "hitls_build.h" #include "bsl_log.h" #include "bsl_log_internal.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_BSL_LOG #define BINGLOG_STR(str) (str) #else #define BINGLOG_STR(str) NULL #endif enum TLS_BINLOG_ID { BINLOG_ID15001 = 15001, BINLOG_ID15002, BINLOG_ID15003, BINLOG_ID15004, BINLOG_ID15005, BINLOG_ID15006, BINLOG_ID15007, BINLOG_ID15008, BINLOG_ID15009, BINLOG_ID15010, BINLOG_ID15011, BINLOG_ID15012, BINLOG_ID15013, BINLOG_ID15014, BINLOG_ID15015, BINLOG_ID15016, BINLOG_ID15017, BINLOG_ID15018, BINLOG_ID15019, BINLOG_ID15020, BINLOG_ID15021, BINLOG_ID15022, BINLOG_ID15023, BINLOG_ID15024, BINLOG_ID15025, BINLOG_ID15026, BINLOG_ID15027, BINLOG_ID15028, BINLOG_ID15029, BINLOG_ID15030, BINLOG_ID15031, BINLOG_ID15032, BINLOG_ID15033, BINLOG_ID15034, BINLOG_ID15035, BINLOG_ID15036, BINLOG_ID15037, BINLOG_ID15038, BINLOG_ID15039, BINLOG_ID15040, BINLOG_ID15041, BINLOG_ID15042, BINLOG_ID15043, BINLOG_ID15044, BINLOG_ID15045, BINLOG_ID15046, BINLOG_ID15047, BINLOG_ID15048, BINLOG_ID15049, BINLOG_ID15050, BINLOG_ID15051, BINLOG_ID15052, BINLOG_ID15053, BINLOG_ID15054, BINLOG_ID15055, BINLOG_ID15056, BINLOG_ID15057, BINLOG_ID15058, BINLOG_ID15059, BINLOG_ID15060, BINLOG_ID15061, BINLOG_ID15062, BINLOG_ID15063, BINLOG_ID15064, BINLOG_ID15065, BINLOG_ID15066, BINLOG_ID15067, BINLOG_ID15068, BINLOG_ID15069, BINLOG_ID15070, BINLOG_ID15071, BINLOG_ID15072, BINLOG_ID15073, BINLOG_ID15074, BINLOG_ID15075, BINLOG_ID15076, BINLOG_ID15077, BINLOG_ID15078, BINLOG_ID15079, BINLOG_ID15080, BINLOG_ID15081, BINLOG_ID15082, BINLOG_ID15083, BINLOG_ID15084, BINLOG_ID15085, BINLOG_ID15086, BINLOG_ID15087, BINLOG_ID15088, BINLOG_ID15089, BINLOG_ID15090, BINLOG_ID15091, BINLOG_ID15092, BINLOG_ID15093, BINLOG_ID15094, BINLOG_ID15095, BINLOG_ID15096, BINLOG_ID15097, BINLOG_ID15098, BINLOG_ID15099, BINLOG_ID15100, BINLOG_ID15101, BINLOG_ID15102, BINLOG_ID15103, BINLOG_ID15104, BINLOG_ID15105, BINLOG_ID15106, BINLOG_ID15107, BINLOG_ID15108, BINLOG_ID15109, BINLOG_ID15110, BINLOG_ID15111, BINLOG_ID15112, BINLOG_ID15113, BINLOG_ID15114, BINLOG_ID15115, BINLOG_ID15116, BINLOG_ID15117, BINLOG_ID15118, BINLOG_ID15119, BINLOG_ID15120, BINLOG_ID15121, BINLOG_ID15122, BINLOG_ID15123, BINLOG_ID15124, BINLOG_ID15125, BINLOG_ID15126, BINLOG_ID15127, BINLOG_ID15128, BINLOG_ID15129, BINLOG_ID15130, BINLOG_ID15131, BINLOG_ID15132, BINLOG_ID15133, BINLOG_ID15134, BINLOG_ID15135, BINLOG_ID15136, BINLOG_ID15137, BINLOG_ID15138, BINLOG_ID15139, BINLOG_ID15140, BINLOG_ID15141, BINLOG_ID15142, BINLOG_ID15143, BINLOG_ID15144, BINLOG_ID15145, BINLOG_ID15146, BINLOG_ID15147, BINLOG_ID15148, BINLOG_ID15149, BINLOG_ID15150, BINLOG_ID15151, BINLOG_ID15152, BINLOG_ID15153, BINLOG_ID15154, BINLOG_ID15155, BINLOG_ID15156, BINLOG_ID15157, BINLOG_ID15158, BINLOG_ID15159, BINLOG_ID15160, BINLOG_ID15161, BINLOG_ID15162, BINLOG_ID15163, BINLOG_ID15164, BINLOG_ID15165, BINLOG_ID15166, BINLOG_ID15167, BINLOG_ID15168, BINLOG_ID15169, BINLOG_ID15170, BINLOG_ID15171, BINLOG_ID15172, BINLOG_ID15173, BINLOG_ID15174, BINLOG_ID15175, BINLOG_ID15176, BINLOG_ID15177, BINLOG_ID15178, BINLOG_ID15179, BINLOG_ID15180, BINLOG_ID15181, BINLOG_ID15182, BINLOG_ID15183, BINLOG_ID15184, BINLOG_ID15185, BINLOG_ID15186, BINLOG_ID15187, BINLOG_ID15188, BINLOG_ID15189, BINLOG_ID15190, BINLOG_ID15191, BINLOG_ID15192, BINLOG_ID15193, BINLOG_ID15194, BINLOG_ID15195, BINLOG_ID15196, BINLOG_ID15197, BINLOG_ID15198, BINLOG_ID15199, BINLOG_ID15200, BINLOG_ID15201, BINLOG_ID15202, BINLOG_ID15203, BINLOG_ID15204, BINLOG_ID15205, BINLOG_ID15206, BINLOG_ID15207, BINLOG_ID15208, BINLOG_ID15209, BINLOG_ID15210, BINLOG_ID15211, BINLOG_ID15212, BINLOG_ID15213, BINLOG_ID15214, BINLOG_ID15215, BINLOG_ID15216, BINLOG_ID15217, BINLOG_ID15218, BINLOG_ID15219, BINLOG_ID15220, BINLOG_ID15221, BINLOG_ID15222, BINLOG_ID15223, BINLOG_ID15224, BINLOG_ID15225, BINLOG_ID15226, BINLOG_ID15227, BINLOG_ID15228, BINLOG_ID15229, BINLOG_ID15230, BINLOG_ID15231, BINLOG_ID15232, BINLOG_ID15233, BINLOG_ID15234, BINLOG_ID15235, BINLOG_ID15236, BINLOG_ID15237, BINLOG_ID15238, BINLOG_ID15239, BINLOG_ID15240, BINLOG_ID15241, BINLOG_ID15242, BINLOG_ID15243, BINLOG_ID15244, BINLOG_ID15245, BINLOG_ID15246, BINLOG_ID15247, BINLOG_ID15248, BINLOG_ID15249, BINLOG_ID15250, BINLOG_ID15251, BINLOG_ID15252, BINLOG_ID15253, BINLOG_ID15254, BINLOG_ID15255, BINLOG_ID15256, BINLOG_ID15257, BINLOG_ID15258, BINLOG_ID15259, BINLOG_ID15260, BINLOG_ID15261, BINLOG_ID15262, BINLOG_ID15263, BINLOG_ID15264, BINLOG_ID15265, BINLOG_ID15266, BINLOG_ID15267, BINLOG_ID15268, BINLOG_ID15269, BINLOG_ID15270, BINLOG_ID15271, BINLOG_ID15272, BINLOG_ID15273, BINLOG_ID15274, BINLOG_ID15275, BINLOG_ID15276, BINLOG_ID15277, BINLOG_ID15278, BINLOG_ID15279, BINLOG_ID15280, BINLOG_ID15281, BINLOG_ID15282, BINLOG_ID15283, BINLOG_ID15284, BINLOG_ID15285, BINLOG_ID15286, BINLOG_ID15287, BINLOG_ID15288, BINLOG_ID15289, BINLOG_ID15290, BINLOG_ID15291, BINLOG_ID15292, BINLOG_ID15293, BINLOG_ID15294, BINLOG_ID15295, BINLOG_ID15296, BINLOG_ID15297, BINLOG_ID15298, BINLOG_ID15299, BINLOG_ID15300, BINLOG_ID15301, BINLOG_ID15302, BINLOG_ID15303, BINLOG_ID15304, BINLOG_ID15305, BINLOG_ID15306, BINLOG_ID15307, BINLOG_ID15308, BINLOG_ID15309, BINLOG_ID15310, BINLOG_ID15311, BINLOG_ID15312, BINLOG_ID15313, BINLOG_ID15314, BINLOG_ID15315, BINLOG_ID15316, BINLOG_ID15317, BINLOG_ID15318, BINLOG_ID15319, BINLOG_ID15320, BINLOG_ID15321, BINLOG_ID15322, BINLOG_ID15323, BINLOG_ID15324, BINLOG_ID15325, BINLOG_ID15326, BINLOG_ID15327, BINLOG_ID15328, BINLOG_ID15329, BINLOG_ID15330, BINLOG_ID15331, BINLOG_ID15332, BINLOG_ID15333, BINLOG_ID15334, BINLOG_ID15335, BINLOG_ID15336, BINLOG_ID15337, BINLOG_ID15338, BINLOG_ID15339, BINLOG_ID15340, BINLOG_ID15341, BINLOG_ID15342, BINLOG_ID15343, BINLOG_ID15344, BINLOG_ID15345, BINLOG_ID15346, BINLOG_ID15347, BINLOG_ID15348, BINLOG_ID15349, BINLOG_ID15350, BINLOG_ID15351, BINLOG_ID15352, BINLOG_ID15353, BINLOG_ID15354, BINLOG_ID15355, BINLOG_ID15356, BINLOG_ID15357, BINLOG_ID15358, BINLOG_ID15359, BINLOG_ID15360, BINLOG_ID15361, BINLOG_ID15362, BINLOG_ID15363, BINLOG_ID15364, BINLOG_ID15365, BINLOG_ID15366, BINLOG_ID15367, BINLOG_ID15368, BINLOG_ID15369, BINLOG_ID15370, BINLOG_ID15371, BINLOG_ID15372, BINLOG_ID15373, BINLOG_ID15374, BINLOG_ID15375, BINLOG_ID15376, BINLOG_ID15377, BINLOG_ID15378, BINLOG_ID15379, BINLOG_ID15380, BINLOG_ID15381, BINLOG_ID15382, BINLOG_ID15383, BINLOG_ID15384, BINLOG_ID15385, BINLOG_ID15386, BINLOG_ID15387, BINLOG_ID15388, BINLOG_ID15389, BINLOG_ID15390, BINLOG_ID15391, BINLOG_ID15392, BINLOG_ID15393, BINLOG_ID15394, BINLOG_ID15395, BINLOG_ID15396, BINLOG_ID15397, BINLOG_ID15398, BINLOG_ID15399, BINLOG_ID15400, BINLOG_ID15401, BINLOG_ID15402, BINLOG_ID15403, BINLOG_ID15404, BINLOG_ID15405, BINLOG_ID15406, BINLOG_ID15407, BINLOG_ID15408, BINLOG_ID15409, BINLOG_ID15410, BINLOG_ID15411, BINLOG_ID15412, BINLOG_ID15413, BINLOG_ID15414, BINLOG_ID15415, BINLOG_ID15416, BINLOG_ID15417, BINLOG_ID15418, BINLOG_ID15419, BINLOG_ID15420, BINLOG_ID15421, BINLOG_ID15422, BINLOG_ID15423, BINLOG_ID15424, BINLOG_ID15425, BINLOG_ID15426, BINLOG_ID15427, BINLOG_ID15428, BINLOG_ID15429, BINLOG_ID15430, BINLOG_ID15431, BINLOG_ID15432, BINLOG_ID15433, BINLOG_ID15434, BINLOG_ID15435, BINLOG_ID15436, BINLOG_ID15437, BINLOG_ID15438, BINLOG_ID15439, BINLOG_ID15440, BINLOG_ID15441, BINLOG_ID15442, BINLOG_ID15443, BINLOG_ID15444, BINLOG_ID15445, BINLOG_ID15446, BINLOG_ID15447, BINLOG_ID15448, BINLOG_ID15449, BINLOG_ID15450, BINLOG_ID15451, BINLOG_ID15452, BINLOG_ID15453, BINLOG_ID15454, BINLOG_ID15455, BINLOG_ID15456, BINLOG_ID15457, BINLOG_ID15458, BINLOG_ID15459, BINLOG_ID15460, BINLOG_ID15461, BINLOG_ID15462, BINLOG_ID15463, BINLOG_ID15464, BINLOG_ID15465, BINLOG_ID15466, BINLOG_ID15467, BINLOG_ID15468, BINLOG_ID15469, BINLOG_ID15470, BINLOG_ID15471, BINLOG_ID15472, BINLOG_ID15473, BINLOG_ID15474, BINLOG_ID15475, BINLOG_ID15476, BINLOG_ID15477, BINLOG_ID15478, BINLOG_ID15479, BINLOG_ID15480, BINLOG_ID15481, BINLOG_ID15482, BINLOG_ID15483, BINLOG_ID15484, BINLOG_ID15485, BINLOG_ID15486, BINLOG_ID15487, BINLOG_ID15488, BINLOG_ID15489, BINLOG_ID15490, BINLOG_ID15491, BINLOG_ID15492, BINLOG_ID15493, BINLOG_ID15494, BINLOG_ID15495, BINLOG_ID15496, BINLOG_ID15497, BINLOG_ID15498, BINLOG_ID15499, BINLOG_ID15500, BINLOG_ID15501, BINLOG_ID15502, BINLOG_ID15503, BINLOG_ID15504, BINLOG_ID15505, BINLOG_ID15506, BINLOG_ID15507, BINLOG_ID15508, BINLOG_ID15509, BINLOG_ID15510, BINLOG_ID15511, BINLOG_ID15512, BINLOG_ID15513, BINLOG_ID15514, BINLOG_ID15515, BINLOG_ID15516, BINLOG_ID15517, BINLOG_ID15518, BINLOG_ID15519, BINLOG_ID15520, BINLOG_ID15521, BINLOG_ID15522, BINLOG_ID15523, BINLOG_ID15524, BINLOG_ID15525, BINLOG_ID15526, BINLOG_ID15527, BINLOG_ID15528, BINLOG_ID15529, BINLOG_ID15530, BINLOG_ID15531, BINLOG_ID15532, BINLOG_ID15533, BINLOG_ID15534, BINLOG_ID15535, BINLOG_ID15536, BINLOG_ID15537, BINLOG_ID15538, BINLOG_ID15539, BINLOG_ID15540, BINLOG_ID15541, BINLOG_ID15542, BINLOG_ID15543, BINLOG_ID15544, BINLOG_ID15545, BINLOG_ID15546, BINLOG_ID15547, BINLOG_ID15548, BINLOG_ID15549, BINLOG_ID15550, BINLOG_ID15551, BINLOG_ID15552, BINLOG_ID15553, BINLOG_ID15554, BINLOG_ID15555, BINLOG_ID15556, BINLOG_ID15557, BINLOG_ID15558, BINLOG_ID15559, BINLOG_ID15560, BINLOG_ID15561, BINLOG_ID15562, BINLOG_ID15563, BINLOG_ID15564, BINLOG_ID15565, BINLOG_ID15566, BINLOG_ID15567, BINLOG_ID15568, BINLOG_ID15569, BINLOG_ID15570, BINLOG_ID15571, BINLOG_ID15572, BINLOG_ID15573, BINLOG_ID15574, BINLOG_ID15575, BINLOG_ID15576, BINLOG_ID15577, BINLOG_ID15578, BINLOG_ID15579, BINLOG_ID15580, BINLOG_ID15581, BINLOG_ID15582, BINLOG_ID15583, BINLOG_ID15584, BINLOG_ID15585, BINLOG_ID15586, BINLOG_ID15587, BINLOG_ID15588, BINLOG_ID15589, BINLOG_ID15590, BINLOG_ID15591, BINLOG_ID15592, BINLOG_ID15593, BINLOG_ID15594, BINLOG_ID15595, BINLOG_ID15596, BINLOG_ID15597, BINLOG_ID15598, BINLOG_ID15599, BINLOG_ID15600, BINLOG_ID15601, BINLOG_ID15602, BINLOG_ID15603, BINLOG_ID15604, BINLOG_ID15605, BINLOG_ID15606, BINLOG_ID15607, BINLOG_ID15608, BINLOG_ID15609, BINLOG_ID15610, BINLOG_ID15611, BINLOG_ID15612, BINLOG_ID15613, BINLOG_ID15614, BINLOG_ID15615, BINLOG_ID15616, BINLOG_ID15617, BINLOG_ID15618, BINLOG_ID15619, BINLOG_ID15620, BINLOG_ID15621, BINLOG_ID15622, BINLOG_ID15623, BINLOG_ID15624, BINLOG_ID15625, BINLOG_ID15626, BINLOG_ID15627, BINLOG_ID15628, BINLOG_ID15629, BINLOG_ID15630, BINLOG_ID15631, BINLOG_ID15632, BINLOG_ID15633, BINLOG_ID15634, BINLOG_ID15635, BINLOG_ID15636, BINLOG_ID15637, BINLOG_ID15638, BINLOG_ID15639, BINLOG_ID15640, BINLOG_ID15641, BINLOG_ID15642, BINLOG_ID15643, BINLOG_ID15644, BINLOG_ID15645, BINLOG_ID15646, BINLOG_ID15647, BINLOG_ID15648, BINLOG_ID15649, BINLOG_ID15650, BINLOG_ID15651, BINLOG_ID15652, BINLOG_ID15653, BINLOG_ID15654, BINLOG_ID15655, BINLOG_ID15656, BINLOG_ID15657, BINLOG_ID15658, BINLOG_ID15659, BINLOG_ID15660, BINLOG_ID15661, BINLOG_ID15662, BINLOG_ID15663, BINLOG_ID15664, BINLOG_ID15665, BINLOG_ID15666, BINLOG_ID15667, BINLOG_ID15668, BINLOG_ID15669, BINLOG_ID15670, BINLOG_ID15671, BINLOG_ID15672, BINLOG_ID15673, BINLOG_ID15674, BINLOG_ID15675, BINLOG_ID15676, BINLOG_ID15677, BINLOG_ID15678, BINLOG_ID15679, BINLOG_ID15680, BINLOG_ID15681, BINLOG_ID15682, BINLOG_ID15683, BINLOG_ID15684, BINLOG_ID15685, BINLOG_ID15686, BINLOG_ID15687, BINLOG_ID15688, BINLOG_ID15689, BINLOG_ID15690, BINLOG_ID15691, BINLOG_ID15692, BINLOG_ID15693, BINLOG_ID15694, BINLOG_ID15695, BINLOG_ID15696, BINLOG_ID15697, BINLOG_ID15698, BINLOG_ID15699, BINLOG_ID15700, BINLOG_ID15701, BINLOG_ID15702, BINLOG_ID15703, BINLOG_ID15704, BINLOG_ID15705, BINLOG_ID15706, BINLOG_ID15707, BINLOG_ID15708, BINLOG_ID15709, BINLOG_ID15710, BINLOG_ID15711, BINLOG_ID15712, BINLOG_ID15713, BINLOG_ID15714, BINLOG_ID15715, BINLOG_ID15716, BINLOG_ID15717, BINLOG_ID15718, BINLOG_ID15719, BINLOG_ID15720, BINLOG_ID15721, BINLOG_ID15722, BINLOG_ID15723, BINLOG_ID15724, BINLOG_ID15725, BINLOG_ID15726, BINLOG_ID15727, BINLOG_ID15728, BINLOG_ID15729, BINLOG_ID15730, BINLOG_ID15731, BINLOG_ID15732, BINLOG_ID15733, BINLOG_ID15734, BINLOG_ID15735, BINLOG_ID15736, BINLOG_ID15737, BINLOG_ID15738, BINLOG_ID15739, BINLOG_ID15740, BINLOG_ID15741, BINLOG_ID15742, BINLOG_ID15743, BINLOG_ID15744, BINLOG_ID15745, BINLOG_ID15746, BINLOG_ID15747, BINLOG_ID15748, BINLOG_ID15749, BINLOG_ID15750, BINLOG_ID15751, BINLOG_ID15752, BINLOG_ID15753, BINLOG_ID15754, BINLOG_ID15755, BINLOG_ID15756, BINLOG_ID15757, BINLOG_ID15758, BINLOG_ID15759, BINLOG_ID15760, BINLOG_ID15761, BINLOG_ID15762, BINLOG_ID15763, BINLOG_ID15764, BINLOG_ID15765, BINLOG_ID15766, BINLOG_ID15767, BINLOG_ID15768, BINLOG_ID15769, BINLOG_ID15770, BINLOG_ID15771, BINLOG_ID15772, BINLOG_ID15773, BINLOG_ID15774, BINLOG_ID15775, BINLOG_ID15776, BINLOG_ID15777, BINLOG_ID15778, BINLOG_ID15779, BINLOG_ID15780, BINLOG_ID15781, BINLOG_ID15782, BINLOG_ID15783, BINLOG_ID15784, BINLOG_ID15785, BINLOG_ID15786, BINLOG_ID15787, BINLOG_ID15788, BINLOG_ID15789, BINLOG_ID15790, BINLOG_ID15791, BINLOG_ID15792, BINLOG_ID15793, BINLOG_ID15794, BINLOG_ID15795, BINLOG_ID15796, BINLOG_ID15797, BINLOG_ID15798, BINLOG_ID15799, BINLOG_ID15800, BINLOG_ID15801, BINLOG_ID15802, BINLOG_ID15803, BINLOG_ID15804, BINLOG_ID15805, BINLOG_ID15806, BINLOG_ID15807, BINLOG_ID15808, BINLOG_ID15809, BINLOG_ID15810, BINLOG_ID15811, BINLOG_ID15812, BINLOG_ID15813, BINLOG_ID15814, BINLOG_ID15815, BINLOG_ID15816, BINLOG_ID15817, BINLOG_ID15818, BINLOG_ID15819, BINLOG_ID15820, BINLOG_ID15821, BINLOG_ID15822, BINLOG_ID15823, BINLOG_ID15824, BINLOG_ID15825, BINLOG_ID15826, BINLOG_ID15827, BINLOG_ID15828, BINLOG_ID15829, BINLOG_ID15830, BINLOG_ID15831, BINLOG_ID15832, BINLOG_ID15833, BINLOG_ID15834, BINLOG_ID15835, BINLOG_ID15836, BINLOG_ID15837, BINLOG_ID15838, BINLOG_ID15839, BINLOG_ID15840, BINLOG_ID15841, BINLOG_ID15842, BINLOG_ID15843, BINLOG_ID15844, BINLOG_ID15845, BINLOG_ID15846, BINLOG_ID15847, BINLOG_ID15848, BINLOG_ID15849, BINLOG_ID15850, BINLOG_ID15851, BINLOG_ID15852, BINLOG_ID15853, BINLOG_ID15854, BINLOG_ID15855, BINLOG_ID15856, BINLOG_ID15857, BINLOG_ID15858, BINLOG_ID15859, BINLOG_ID15860, BINLOG_ID15861, BINLOG_ID15862, BINLOG_ID15863, BINLOG_ID15864, BINLOG_ID15865, BINLOG_ID15866, BINLOG_ID15867, BINLOG_ID15868, BINLOG_ID15869, BINLOG_ID15870, BINLOG_ID15871, BINLOG_ID15872, BINLOG_ID15873, BINLOG_ID15874, BINLOG_ID15875, BINLOG_ID15876, BINLOG_ID15877, BINLOG_ID15878, BINLOG_ID15879, BINLOG_ID15880, BINLOG_ID15881, BINLOG_ID15882, BINLOG_ID15883, BINLOG_ID15884, BINLOG_ID15885, BINLOG_ID15886, BINLOG_ID15887, BINLOG_ID15888, BINLOG_ID15889, BINLOG_ID15890, BINLOG_ID15891, BINLOG_ID15892, BINLOG_ID15893, BINLOG_ID15894, BINLOG_ID15895, BINLOG_ID15896, BINLOG_ID15897, BINLOG_ID15898, BINLOG_ID15899, BINLOG_ID15900, BINLOG_ID15901, BINLOG_ID15902, BINLOG_ID15903, BINLOG_ID15904, BINLOG_ID15905, BINLOG_ID15906, BINLOG_ID15907, BINLOG_ID15908, BINLOG_ID15909, BINLOG_ID15910, BINLOG_ID15911, BINLOG_ID15912, BINLOG_ID15913, BINLOG_ID15914, BINLOG_ID15915, BINLOG_ID15916, BINLOG_ID15917, BINLOG_ID15918, BINLOG_ID15919, BINLOG_ID15920, BINLOG_ID15921, BINLOG_ID15922, BINLOG_ID15923, BINLOG_ID15924, BINLOG_ID15925, BINLOG_ID15926, BINLOG_ID15927, BINLOG_ID15928, BINLOG_ID15929, BINLOG_ID15930, BINLOG_ID15931, BINLOG_ID15932, BINLOG_ID15933, BINLOG_ID15934, BINLOG_ID15935, BINLOG_ID15936, BINLOG_ID15937, BINLOG_ID15938, BINLOG_ID15939, BINLOG_ID15940, BINLOG_ID15941, BINLOG_ID15942, BINLOG_ID15943, BINLOG_ID15944, BINLOG_ID15945, BINLOG_ID15946, BINLOG_ID15947, BINLOG_ID15948, BINLOG_ID15949, BINLOG_ID15950, BINLOG_ID15951, BINLOG_ID15952, BINLOG_ID15953, BINLOG_ID15954, BINLOG_ID15955, BINLOG_ID15956, BINLOG_ID15957, BINLOG_ID15958, BINLOG_ID15959, BINLOG_ID15960, BINLOG_ID15961, BINLOG_ID15962, BINLOG_ID15963, BINLOG_ID15964, BINLOG_ID15965, BINLOG_ID15966, BINLOG_ID15967, BINLOG_ID15968, BINLOG_ID15969, BINLOG_ID15970, BINLOG_ID15971, BINLOG_ID15972, BINLOG_ID15973, BINLOG_ID15974, BINLOG_ID15975, BINLOG_ID15976, BINLOG_ID15977, BINLOG_ID15978, BINLOG_ID15979, BINLOG_ID15980, BINLOG_ID15981, BINLOG_ID15982, BINLOG_ID15983, BINLOG_ID15984, BINLOG_ID15985, BINLOG_ID15986, BINLOG_ID15987, BINLOG_ID15988, BINLOG_ID15989, BINLOG_ID15990, BINLOG_ID15991, BINLOG_ID15992, BINLOG_ID15993, BINLOG_ID15994, BINLOG_ID15995, BINLOG_ID15996, BINLOG_ID15997, BINLOG_ID15998, BINLOG_ID15999, BINLOG_ID16000, BINLOG_ID16001, BINLOG_ID16002, BINLOG_ID16003, BINLOG_ID16004, BINLOG_ID16005, BINLOG_ID16006, BINLOG_ID16007, BINLOG_ID16008, BINLOG_ID16009, BINLOG_ID16010, BINLOG_ID16011, BINLOG_ID16012, BINLOG_ID16013, BINLOG_ID16014, BINLOG_ID16015, BINLOG_ID16016, BINLOG_ID16017, BINLOG_ID16018, BINLOG_ID16019, BINLOG_ID16020, BINLOG_ID16021, BINLOG_ID16022, BINLOG_ID16023, BINLOG_ID16024, BINLOG_ID16025, BINLOG_ID16026, BINLOG_ID16027, BINLOG_ID16028, BINLOG_ID16029, BINLOG_ID16030, BINLOG_ID16031, BINLOG_ID16032, BINLOG_ID16033, BINLOG_ID16034, BINLOG_ID16035, BINLOG_ID16036, BINLOG_ID16037, BINLOG_ID16038, BINLOG_ID16039, BINLOG_ID16040, BINLOG_ID16041, BINLOG_ID16042, BINLOG_ID16043, BINLOG_ID16044, BINLOG_ID16045, BINLOG_ID16046, BINLOG_ID16047, BINLOG_ID16048, BINLOG_ID16049, BINLOG_ID16050, BINLOG_ID16051, BINLOG_ID16052, BINLOG_ID16053, BINLOG_ID16054, BINLOG_ID16055, BINLOG_ID16056, BINLOG_ID16057, BINLOG_ID16058, BINLOG_ID16059, BINLOG_ID16060, BINLOG_ID16061, BINLOG_ID16062, BINLOG_ID16063, BINLOG_ID16064, BINLOG_ID16065, BINLOG_ID16066, BINLOG_ID16067, BINLOG_ID16068, BINLOG_ID16069, BINLOG_ID16070, BINLOG_ID16071, BINLOG_ID16072, BINLOG_ID16073, BINLOG_ID16074, BINLOG_ID16075, BINLOG_ID16076, BINLOG_ID16077, BINLOG_ID16078, BINLOG_ID16079, BINLOG_ID16080, BINLOG_ID16081, BINLOG_ID16082, BINLOG_ID16083, BINLOG_ID16084, BINLOG_ID16085, BINLOG_ID16086, BINLOG_ID16087, BINLOG_ID16088, BINLOG_ID16089, BINLOG_ID16090, BINLOG_ID16091, BINLOG_ID16092, BINLOG_ID16093, BINLOG_ID16094, BINLOG_ID16095, BINLOG_ID16096, BINLOG_ID16097, BINLOG_ID16098, BINLOG_ID16099, BINLOG_ID16100, BINLOG_ID16101, BINLOG_ID16102, BINLOG_ID16103, BINLOG_ID16104, BINLOG_ID16105, BINLOG_ID16106, BINLOG_ID16107, BINLOG_ID16108, BINLOG_ID16109, BINLOG_ID16110, BINLOG_ID16111, BINLOG_ID16112, BINLOG_ID16113, BINLOG_ID16114, BINLOG_ID16115, BINLOG_ID16116, BINLOG_ID16117, BINLOG_ID16118, BINLOG_ID16119, BINLOG_ID16120, BINLOG_ID16121, BINLOG_ID16122, BINLOG_ID16123, BINLOG_ID16124, BINLOG_ID16125, BINLOG_ID16126, BINLOG_ID16127, BINLOG_ID16128, BINLOG_ID16129, BINLOG_ID16130, BINLOG_ID16131, BINLOG_ID16132, BINLOG_ID16133, BINLOG_ID16134, BINLOG_ID16135, BINLOG_ID16136, BINLOG_ID16137, BINLOG_ID16138, BINLOG_ID16139, BINLOG_ID16140, BINLOG_ID16141, BINLOG_ID16142, BINLOG_ID16143, BINLOG_ID16144, BINLOG_ID16145, BINLOG_ID16146, BINLOG_ID16147, BINLOG_ID16148, BINLOG_ID16149, BINLOG_ID16150, BINLOG_ID16151, BINLOG_ID16152, BINLOG_ID16153, BINLOG_ID16154, BINLOG_ID16155, BINLOG_ID16156, BINLOG_ID16157, BINLOG_ID16158, BINLOG_ID16159, BINLOG_ID16160, BINLOG_ID16161, BINLOG_ID16162, BINLOG_ID16163, BINLOG_ID16164, BINLOG_ID16165, BINLOG_ID16166, BINLOG_ID16167, BINLOG_ID16168, BINLOG_ID16169, BINLOG_ID16170, BINLOG_ID16171, BINLOG_ID16172, BINLOG_ID16173, BINLOG_ID16174, BINLOG_ID16175, BINLOG_ID16176, BINLOG_ID16177, BINLOG_ID16178, BINLOG_ID16179, BINLOG_ID16180, BINLOG_ID16181, BINLOG_ID16182, BINLOG_ID16183, BINLOG_ID16184, BINLOG_ID16185, BINLOG_ID16186, BINLOG_ID16187, BINLOG_ID16188, BINLOG_ID16189, BINLOG_ID16190, BINLOG_ID16191, BINLOG_ID16192, BINLOG_ID16193, BINLOG_ID16194, BINLOG_ID16195, BINLOG_ID16196, BINLOG_ID16197, BINLOG_ID16198, BINLOG_ID16199, BINLOG_ID16200, BINLOG_ID16201, BINLOG_ID16202, BINLOG_ID16203, BINLOG_ID16204, BINLOG_ID16205, BINLOG_ID16206, BINLOG_ID16207, BINLOG_ID16208, BINLOG_ID16209, BINLOG_ID16210, BINLOG_ID16211, BINLOG_ID16212, BINLOG_ID16213, BINLOG_ID16214, BINLOG_ID16215, BINLOG_ID16216, BINLOG_ID16217, BINLOG_ID16218, BINLOG_ID16219, BINLOG_ID16220, BINLOG_ID16221, BINLOG_ID16222, BINLOG_ID16223, BINLOG_ID16224, BINLOG_ID16225, BINLOG_ID16226, BINLOG_ID16227, BINLOG_ID16228, BINLOG_ID16229, BINLOG_ID16230, BINLOG_ID16231, BINLOG_ID16232, BINLOG_ID16233, BINLOG_ID16234, BINLOG_ID16235, BINLOG_ID16236, BINLOG_ID16237, BINLOG_ID16238, BINLOG_ID16239, BINLOG_ID16240, BINLOG_ID16241, BINLOG_ID16242, BINLOG_ID16243, BINLOG_ID16244, BINLOG_ID16245, BINLOG_ID16246, BINLOG_ID16247, BINLOG_ID16248, BINLOG_ID16249, BINLOG_ID16250, BINLOG_ID16251, BINLOG_ID16252, BINLOG_ID16253, BINLOG_ID16254, BINLOG_ID16255, BINLOG_ID16256, BINLOG_ID16257, BINLOG_ID16258, BINLOG_ID16259, BINLOG_ID16260, BINLOG_ID16261, BINLOG_ID16262, BINLOG_ID16263, BINLOG_ID16264, BINLOG_ID16265, BINLOG_ID16266, BINLOG_ID16267, BINLOG_ID16268, BINLOG_ID16269, BINLOG_ID16270, BINLOG_ID16271, BINLOG_ID16272, BINLOG_ID16273, BINLOG_ID16274, BINLOG_ID16275, BINLOG_ID16276, BINLOG_ID16277, BINLOG_ID16278, BINLOG_ID16279, BINLOG_ID16280, BINLOG_ID16281, BINLOG_ID16282, BINLOG_ID16283, BINLOG_ID16284, BINLOG_ID16285, BINLOG_ID16286, BINLOG_ID16287, BINLOG_ID16288, BINLOG_ID16289, BINLOG_ID16290, BINLOG_ID16291, BINLOG_ID16292, BINLOG_ID16293, BINLOG_ID16294, BINLOG_ID16295, BINLOG_ID16296, BINLOG_ID16297, BINLOG_ID16298, BINLOG_ID16299, BINLOG_ID16300, BINLOG_ID16301, BINLOG_ID16302, BINLOG_ID16303, BINLOG_ID16304, BINLOG_ID16305, BINLOG_ID16306, BINLOG_ID16307, BINLOG_ID16308, BINLOG_ID16309, BINLOG_ID16310, BINLOG_ID16311, BINLOG_ID16312, BINLOG_ID16313, BINLOG_ID16314, BINLOG_ID16315, BINLOG_ID16316, BINLOG_ID16317, BINLOG_ID16318, BINLOG_ID16319, BINLOG_ID16320, BINLOG_ID16321, BINLOG_ID16322, BINLOG_ID16323, BINLOG_ID16324, BINLOG_ID16325, BINLOG_ID16326, BINLOG_ID16327, BINLOG_ID16328, BINLOG_ID16329, BINLOG_ID16330, BINLOG_ID16331, BINLOG_ID16332, BINLOG_ID16333, BINLOG_ID16334, BINLOG_ID16335, BINLOG_ID16336, BINLOG_ID16337, BINLOG_ID16338, BINLOG_ID16339, BINLOG_ID16340, BINLOG_ID16341, BINLOG_ID16342, BINLOG_ID16343, BINLOG_ID16344, BINLOG_ID16345, BINLOG_ID16346, BINLOG_ID16347, BINLOG_ID16348, BINLOG_ID16349, BINLOG_ID16350, BINLOG_ID16351, BINLOG_ID16352, BINLOG_ID16353, BINLOG_ID16354, BINLOG_ID16355, BINLOG_ID16356, BINLOG_ID16357, BINLOG_ID16358, BINLOG_ID16359, BINLOG_ID16360, BINLOG_ID16361, BINLOG_ID16362, BINLOG_ID16363, BINLOG_ID16364, BINLOG_ID16365, BINLOG_ID16366, BINLOG_ID16367, BINLOG_ID16368, BINLOG_ID16369, BINLOG_ID16370, BINLOG_ID16371, BINLOG_ID16372, BINLOG_ID16373, BINLOG_ID16374, BINLOG_ID16375, BINLOG_ID16376, BINLOG_ID16377, BINLOG_ID16378, BINLOG_ID16379, BINLOG_ID16380, BINLOG_ID16381, BINLOG_ID16382, BINLOG_ID16383, BINLOG_ID16384, BINLOG_ID16385, BINLOG_ID16386, BINLOG_ID16387, BINLOG_ID16388, BINLOG_ID16389, BINLOG_ID16390, BINLOG_ID16391, BINLOG_ID16392, BINLOG_ID16393, BINLOG_ID16394, BINLOG_ID16395, BINLOG_ID16396, BINLOG_ID16397, BINLOG_ID16398, BINLOG_ID16399, BINLOG_ID16400, BINLOG_ID16401, BINLOG_ID16402, BINLOG_ID16403, BINLOG_ID16404, BINLOG_ID16405, BINLOG_ID16406, BINLOG_ID16407, BINLOG_ID16408, BINLOG_ID16409, BINLOG_ID16410, BINLOG_ID16411, BINLOG_ID16412, BINLOG_ID16413, BINLOG_ID16414, BINLOG_ID16415, BINLOG_ID16416, BINLOG_ID16417, BINLOG_ID16418, BINLOG_ID16419, BINLOG_ID16420, BINLOG_ID16421, BINLOG_ID16422, BINLOG_ID16423, BINLOG_ID16424, BINLOG_ID16425, BINLOG_ID16426, BINLOG_ID16427, BINLOG_ID16428, BINLOG_ID16429, BINLOG_ID16430, BINLOG_ID16431, BINLOG_ID16432, BINLOG_ID16433, BINLOG_ID16434, BINLOG_ID16435, BINLOG_ID16436, BINLOG_ID16437, BINLOG_ID16438, BINLOG_ID16439, BINLOG_ID16440, BINLOG_ID16441, BINLOG_ID16442, BINLOG_ID16443, BINLOG_ID16444, BINLOG_ID16445, BINLOG_ID16446, BINLOG_ID16447, BINLOG_ID16448, BINLOG_ID16449, BINLOG_ID16450, BINLOG_ID16451, BINLOG_ID16452, BINLOG_ID16453, BINLOG_ID16454, BINLOG_ID16455, BINLOG_ID16456, BINLOG_ID16457, BINLOG_ID16458, BINLOG_ID16459, BINLOG_ID16460, BINLOG_ID16461, BINLOG_ID16462, BINLOG_ID16463, BINLOG_ID16464, BINLOG_ID16465, BINLOG_ID16466, BINLOG_ID16467, BINLOG_ID16468, BINLOG_ID16469, BINLOG_ID16470, BINLOG_ID16471, BINLOG_ID16472, BINLOG_ID16473, BINLOG_ID16474, BINLOG_ID16475, BINLOG_ID16476, BINLOG_ID16477, BINLOG_ID16478, BINLOG_ID16479, BINLOG_ID16480, BINLOG_ID16481, BINLOG_ID16482, BINLOG_ID16483, BINLOG_ID16484, BINLOG_ID16485, BINLOG_ID16486, BINLOG_ID16487, BINLOG_ID16488, BINLOG_ID16489, BINLOG_ID16490, BINLOG_ID16491, BINLOG_ID16492, BINLOG_ID16493, BINLOG_ID16494, BINLOG_ID16495, BINLOG_ID16496, BINLOG_ID16497, BINLOG_ID16498, BINLOG_ID16499, BINLOG_ID16500, BINLOG_ID16501, BINLOG_ID16502, BINLOG_ID16503, BINLOG_ID16504, BINLOG_ID16505, BINLOG_ID16506, BINLOG_ID16507, BINLOG_ID16508, BINLOG_ID16509, BINLOG_ID16510, BINLOG_ID16511, BINLOG_ID16512, BINLOG_ID16513, BINLOG_ID16514, BINLOG_ID16515, BINLOG_ID16516, BINLOG_ID16517, BINLOG_ID16518, BINLOG_ID16519, BINLOG_ID16520, BINLOG_ID16521, BINLOG_ID16522, BINLOG_ID16523, BINLOG_ID16524, BINLOG_ID16525, BINLOG_ID16526, BINLOG_ID16527, BINLOG_ID16528, BINLOG_ID16529, BINLOG_ID16530, BINLOG_ID16531, BINLOG_ID16532, BINLOG_ID16533, BINLOG_ID16534, BINLOG_ID16535, BINLOG_ID16536, BINLOG_ID16537, BINLOG_ID16538, BINLOG_ID16539, BINLOG_ID16540, BINLOG_ID16541, BINLOG_ID16542, BINLOG_ID16543, BINLOG_ID16544, BINLOG_ID16545, BINLOG_ID16546, BINLOG_ID16547, BINLOG_ID16548, BINLOG_ID16549, BINLOG_ID16550, BINLOG_ID16551, BINLOG_ID16552, BINLOG_ID16553, BINLOG_ID16554, BINLOG_ID16555, BINLOG_ID16556, BINLOG_ID16557, BINLOG_ID16558, BINLOG_ID16559, BINLOG_ID16560, BINLOG_ID16561, BINLOG_ID16562, BINLOG_ID16563, BINLOG_ID16564, BINLOG_ID16565, BINLOG_ID16566, BINLOG_ID16567, BINLOG_ID16568, BINLOG_ID16569, BINLOG_ID16570, BINLOG_ID16571, BINLOG_ID16572, BINLOG_ID16573, BINLOG_ID16574, BINLOG_ID16575, BINLOG_ID16576, BINLOG_ID16577, BINLOG_ID16578, BINLOG_ID16579, BINLOG_ID16580, BINLOG_ID16581, BINLOG_ID16582, BINLOG_ID16583, BINLOG_ID16584, BINLOG_ID16585, BINLOG_ID16586, BINLOG_ID16587, BINLOG_ID16588, BINLOG_ID16589, BINLOG_ID16590, BINLOG_ID16591, BINLOG_ID16592, BINLOG_ID16593, BINLOG_ID16594, BINLOG_ID16595, BINLOG_ID16596, BINLOG_ID16597, BINLOG_ID16598, BINLOG_ID16599, BINLOG_ID16600, BINLOG_ID16601, BINLOG_ID16602, BINLOG_ID16603, BINLOG_ID16604, BINLOG_ID16605, BINLOG_ID16606, BINLOG_ID16607, BINLOG_ID16608, BINLOG_ID16609, BINLOG_ID16610, BINLOG_ID16611, BINLOG_ID16612, BINLOG_ID16613, BINLOG_ID16614, BINLOG_ID16615, BINLOG_ID16616, BINLOG_ID16617, BINLOG_ID16618, BINLOG_ID16619, BINLOG_ID16620, BINLOG_ID16621, BINLOG_ID16622, BINLOG_ID16623, BINLOG_ID16624, BINLOG_ID16625, BINLOG_ID16626, BINLOG_ID16627, BINLOG_ID16628, BINLOG_ID16629, BINLOG_ID16630, BINLOG_ID16631, BINLOG_ID16632, BINLOG_ID16633, BINLOG_ID16634, BINLOG_ID16635, BINLOG_ID16636, BINLOG_ID16637, BINLOG_ID16638, BINLOG_ID16639, BINLOG_ID16640, BINLOG_ID16641, BINLOG_ID16642, BINLOG_ID16643, BINLOG_ID16644, BINLOG_ID16645, BINLOG_ID16646, BINLOG_ID16647, BINLOG_ID16648, BINLOG_ID16649, BINLOG_ID16650, BINLOG_ID16651, BINLOG_ID16652, BINLOG_ID16653, BINLOG_ID16654, BINLOG_ID16655, BINLOG_ID16656, BINLOG_ID16657, BINLOG_ID16658, BINLOG_ID16659, BINLOG_ID16660, BINLOG_ID16661, BINLOG_ID16662, BINLOG_ID16663, BINLOG_ID16664, BINLOG_ID16665, BINLOG_ID16666, BINLOG_ID16667, BINLOG_ID16668, BINLOG_ID16669, BINLOG_ID16670, BINLOG_ID16671, BINLOG_ID16672, BINLOG_ID16673, BINLOG_ID16674, BINLOG_ID16675, BINLOG_ID16676, BINLOG_ID16677, BINLOG_ID16678, BINLOG_ID16679, BINLOG_ID16680, BINLOG_ID16681, BINLOG_ID16682, BINLOG_ID16683, BINLOG_ID16684, BINLOG_ID16685, BINLOG_ID16686, BINLOG_ID16687, BINLOG_ID16688, BINLOG_ID16689, BINLOG_ID16690, BINLOG_ID16691, BINLOG_ID16692, BINLOG_ID16693, BINLOG_ID16694, BINLOG_ID16695, BINLOG_ID16696, BINLOG_ID16697, BINLOG_ID16698, BINLOG_ID16699, BINLOG_ID16700, BINLOG_ID16701, BINLOG_ID16702, BINLOG_ID16703, BINLOG_ID16704, BINLOG_ID16705, BINLOG_ID16706, BINLOG_ID16707, BINLOG_ID16708, BINLOG_ID16709, BINLOG_ID16710, BINLOG_ID16711, BINLOG_ID16712, BINLOG_ID16713, BINLOG_ID16714, BINLOG_ID16715, BINLOG_ID16716, BINLOG_ID16717, BINLOG_ID16718, BINLOG_ID16719, BINLOG_ID16720, BINLOG_ID16721, BINLOG_ID16722, BINLOG_ID16723, BINLOG_ID16724, BINLOG_ID16725, BINLOG_ID16726, BINLOG_ID16727, BINLOG_ID16728, BINLOG_ID16729, BINLOG_ID16730, BINLOG_ID16731, BINLOG_ID16732, BINLOG_ID16733, BINLOG_ID16734, BINLOG_ID16735, BINLOG_ID16736, BINLOG_ID16737, BINLOG_ID16738, BINLOG_ID16739, BINLOG_ID16740, BINLOG_ID16741, BINLOG_ID16742, BINLOG_ID16743, BINLOG_ID16744, BINLOG_ID16745, BINLOG_ID16746, BINLOG_ID16747, BINLOG_ID16748, BINLOG_ID16749, BINLOG_ID16750, BINLOG_ID16751, BINLOG_ID16752, BINLOG_ID16753, BINLOG_ID16754, BINLOG_ID16755, BINLOG_ID16756, BINLOG_ID16757, BINLOG_ID16758, BINLOG_ID16759, BINLOG_ID16760, BINLOG_ID16761, BINLOG_ID16762, BINLOG_ID16763, BINLOG_ID16764, BINLOG_ID16765, BINLOG_ID16766, BINLOG_ID16767, BINLOG_ID16768, BINLOG_ID16769, BINLOG_ID16770, BINLOG_ID16771, BINLOG_ID16772, BINLOG_ID16773, BINLOG_ID16774, BINLOG_ID16775, BINLOG_ID16776, BINLOG_ID16777, BINLOG_ID16778, BINLOG_ID16779, BINLOG_ID16780, BINLOG_ID16781, BINLOG_ID16782, BINLOG_ID16783, BINLOG_ID16784, BINLOG_ID16785, BINLOG_ID16786, BINLOG_ID16787, BINLOG_ID16788, BINLOG_ID16789, BINLOG_ID16790, BINLOG_ID16791, BINLOG_ID16792, BINLOG_ID16793, BINLOG_ID16794, BINLOG_ID16795, BINLOG_ID16796, BINLOG_ID16797, BINLOG_ID16798, BINLOG_ID16799, BINLOG_ID16800, BINLOG_ID16801, BINLOG_ID16802, BINLOG_ID16803, BINLOG_ID16804, BINLOG_ID16805, BINLOG_ID16806, BINLOG_ID16807, BINLOG_ID16808, BINLOG_ID16809, BINLOG_ID16810, BINLOG_ID16811, BINLOG_ID16812, BINLOG_ID16813, BINLOG_ID16814, BINLOG_ID16815, BINLOG_ID16816, BINLOG_ID16817, BINLOG_ID16818, BINLOG_ID16819, BINLOG_ID16820, BINLOG_ID16821, BINLOG_ID16822, BINLOG_ID16823, BINLOG_ID16824, BINLOG_ID16825, BINLOG_ID16826, BINLOG_ID16827, BINLOG_ID16828, BINLOG_ID16829, BINLOG_ID16830, BINLOG_ID16831, BINLOG_ID16832, BINLOG_ID16833, BINLOG_ID16834, BINLOG_ID16835, BINLOG_ID16836, BINLOG_ID16837, BINLOG_ID16838, BINLOG_ID16839, BINLOG_ID16840, BINLOG_ID16841, BINLOG_ID16842, BINLOG_ID16843, BINLOG_ID16844, BINLOG_ID16845, BINLOG_ID16846, BINLOG_ID16847, BINLOG_ID16848, BINLOG_ID16849, BINLOG_ID16850, BINLOG_ID16851, BINLOG_ID16852, BINLOG_ID16853, BINLOG_ID16854, BINLOG_ID16855, BINLOG_ID16856, BINLOG_ID16857, BINLOG_ID16858, BINLOG_ID16859, BINLOG_ID16860, BINLOG_ID16861, BINLOG_ID16862, BINLOG_ID16863, BINLOG_ID16864, BINLOG_ID16865, BINLOG_ID16866, BINLOG_ID16867, BINLOG_ID16868, BINLOG_ID16869, BINLOG_ID16870, BINLOG_ID16871, BINLOG_ID16872, BINLOG_ID16873, BINLOG_ID16874, BINLOG_ID16875, BINLOG_ID16876, BINLOG_ID16877, BINLOG_ID16878, BINLOG_ID16879, BINLOG_ID16880, BINLOG_ID16881, BINLOG_ID16882, BINLOG_ID16883, BINLOG_ID16884, BINLOG_ID16885, BINLOG_ID16886, BINLOG_ID16887, BINLOG_ID16888, BINLOG_ID16889, BINLOG_ID16890, BINLOG_ID16891, BINLOG_ID16892, BINLOG_ID16893, BINLOG_ID16894, BINLOG_ID16895, BINLOG_ID16896, BINLOG_ID16897, BINLOG_ID16898, BINLOG_ID16899, BINLOG_ID16900, BINLOG_ID16901, BINLOG_ID16902, BINLOG_ID16903, BINLOG_ID16904, BINLOG_ID16905, BINLOG_ID16906, BINLOG_ID16907, BINLOG_ID16908, BINLOG_ID16909, BINLOG_ID16910, BINLOG_ID16911, BINLOG_ID16912, BINLOG_ID16913, BINLOG_ID16914, BINLOG_ID16915, BINLOG_ID16916, BINLOG_ID16917, BINLOG_ID16918, BINLOG_ID16919, BINLOG_ID16920, BINLOG_ID16921, BINLOG_ID16922, BINLOG_ID16923, BINLOG_ID16924, BINLOG_ID16925, BINLOG_ID16926, BINLOG_ID16927, BINLOG_ID16928, BINLOG_ID16929, BINLOG_ID16930, BINLOG_ID16931, BINLOG_ID16932, BINLOG_ID16933, BINLOG_ID16934, BINLOG_ID16935, BINLOG_ID16936, BINLOG_ID16937, BINLOG_ID16938, BINLOG_ID16939, BINLOG_ID16940, BINLOG_ID16941, BINLOG_ID16942, BINLOG_ID16943, BINLOG_ID16944, BINLOG_ID16945, BINLOG_ID16946, BINLOG_ID16947, BINLOG_ID16948, BINLOG_ID16949, BINLOG_ID16950, BINLOG_ID16951, BINLOG_ID16952, BINLOG_ID16953, BINLOG_ID16954, BINLOG_ID16955, BINLOG_ID16956, BINLOG_ID16957, BINLOG_ID16958, BINLOG_ID16959, BINLOG_ID16960, BINLOG_ID16961, BINLOG_ID16962, BINLOG_ID16963, BINLOG_ID16964, BINLOG_ID16965, BINLOG_ID16966, BINLOG_ID16967, BINLOG_ID16968, BINLOG_ID16969, BINLOG_ID16970, BINLOG_ID16971, BINLOG_ID16972, BINLOG_ID16973, BINLOG_ID16974, BINLOG_ID16975, BINLOG_ID16976, BINLOG_ID16977, BINLOG_ID16978, BINLOG_ID16979, BINLOG_ID16980, BINLOG_ID16981, BINLOG_ID16982, BINLOG_ID16983, BINLOG_ID16984, BINLOG_ID16985, BINLOG_ID16986, BINLOG_ID16987, BINLOG_ID16988, BINLOG_ID16989, BINLOG_ID16990, BINLOG_ID16991, BINLOG_ID16992, BINLOG_ID16993, BINLOG_ID16994, BINLOG_ID16995, BINLOG_ID16996, BINLOG_ID16997, BINLOG_ID16998, BINLOG_ID16999, BINLOG_ID17000, BINLOG_ID17001, BINLOG_ID17002, BINLOG_ID17003, BINLOG_ID17004, BINLOG_ID17005, BINLOG_ID17006, BINLOG_ID17007, BINLOG_ID17008, BINLOG_ID17009, BINLOG_ID17010, BINLOG_ID17011, BINLOG_ID17012, BINLOG_ID17013, BINLOG_ID17014, BINLOG_ID17015, BINLOG_ID17016, BINLOG_ID17017, BINLOG_ID17018, BINLOG_ID17019, BINLOG_ID17020, BINLOG_ID17021, BINLOG_ID17022, BINLOG_ID17023, BINLOG_ID17024, BINLOG_ID17025, BINLOG_ID17026, BINLOG_ID17027, BINLOG_ID17028, BINLOG_ID17029, BINLOG_ID17030, BINLOG_ID17031, BINLOG_ID17032, BINLOG_ID17033, BINLOG_ID17034, BINLOG_ID17035, BINLOG_ID17036, BINLOG_ID17037, BINLOG_ID17038, BINLOG_ID17039, BINLOG_ID17040, BINLOG_ID17041, BINLOG_ID17042, BINLOG_ID17043, BINLOG_ID17044, BINLOG_ID17045, BINLOG_ID17046, BINLOG_ID17047, BINLOG_ID17048, BINLOG_ID17049, BINLOG_ID17050, BINLOG_ID17051, BINLOG_ID17052, BINLOG_ID17053, BINLOG_ID17054, BINLOG_ID17055, BINLOG_ID17056, BINLOG_ID17057, BINLOG_ID17058, BINLOG_ID17059, BINLOG_ID17060, BINLOG_ID17061, BINLOG_ID17062, BINLOG_ID17063, BINLOG_ID17064, BINLOG_ID17065, BINLOG_ID17066, BINLOG_ID17067, BINLOG_ID17068, BINLOG_ID17069, BINLOG_ID17070, BINLOG_ID17071, BINLOG_ID17072, BINLOG_ID17073, BINLOG_ID17074, BINLOG_ID17075, BINLOG_ID17076, BINLOG_ID17077, BINLOG_ID17078, BINLOG_ID17079, BINLOG_ID17080, BINLOG_ID17081, BINLOG_ID17082, BINLOG_ID17083, BINLOG_ID17084, BINLOG_ID17085, BINLOG_ID17086, BINLOG_ID17087, BINLOG_ID17088, BINLOG_ID17089, BINLOG_ID17090, BINLOG_ID17091, BINLOG_ID17092, BINLOG_ID17093, BINLOG_ID17094, BINLOG_ID17095, BINLOG_ID17096, BINLOG_ID17097, BINLOG_ID17098, BINLOG_ID17099, BINLOG_ID17100, BINLOG_ID17101, BINLOG_ID17102, BINLOG_ID17103, BINLOG_ID17104, BINLOG_ID17105, BINLOG_ID17106, BINLOG_ID17107, BINLOG_ID17108, BINLOG_ID17109, BINLOG_ID17110, BINLOG_ID17111, BINLOG_ID17112, BINLOG_ID17113, BINLOG_ID17114, BINLOG_ID17115, BINLOG_ID17116, BINLOG_ID17117, BINLOG_ID17118, BINLOG_ID17119, BINLOG_ID17120, BINLOG_ID17121, BINLOG_ID17122, BINLOG_ID17123, BINLOG_ID17124, BINLOG_ID17125, BINLOG_ID17126, BINLOG_ID17127, BINLOG_ID17128, BINLOG_ID17129, BINLOG_ID17130, BINLOG_ID17131, BINLOG_ID17132, BINLOG_ID17133, BINLOG_ID17134, BINLOG_ID17135, BINLOG_ID17136, BINLOG_ID17137, BINLOG_ID17138, BINLOG_ID17139, BINLOG_ID17140, BINLOG_ID17141, BINLOG_ID17142, BINLOG_ID17143, BINLOG_ID17144, BINLOG_ID17145, BINLOG_ID17146, BINLOG_ID17147, BINLOG_ID17148, BINLOG_ID17149, BINLOG_ID17150, BINLOG_ID17151, BINLOG_ID17152, BINLOG_ID17153, BINLOG_ID17154, BINLOG_ID17155, BINLOG_ID17156, BINLOG_ID17157, BINLOG_ID17158, BINLOG_ID17159, BINLOG_ID17160, BINLOG_ID17161, BINLOG_ID17162, BINLOG_ID17163, BINLOG_ID17164, BINLOG_ID17165, BINLOG_ID17166, BINLOG_ID17167, BINLOG_ID17168, BINLOG_ID17169, BINLOG_ID17170, BINLOG_ID17171, BINLOG_ID17172, BINLOG_ID17173, BINLOG_ID17174, BINLOG_ID17175, BINLOG_ID17176, BINLOG_ID17177, BINLOG_ID17178, BINLOG_ID17179, BINLOG_ID17180, BINLOG_ID17181, BINLOG_ID17182, BINLOG_ID17183, BINLOG_ID17184, BINLOG_ID17185, BINLOG_ID17186, BINLOG_ID17187, BINLOG_ID17188, BINLOG_ID17189, BINLOG_ID17190, BINLOG_ID17191, BINLOG_ID17192, BINLOG_ID17193, BINLOG_ID17194, BINLOG_ID17195, BINLOG_ID17196, BINLOG_ID17197, BINLOG_ID17198, BINLOG_ID17199, BINLOG_ID17200, BINLOG_ID17201, BINLOG_ID17202, BINLOG_ID17203, BINLOG_ID17204, BINLOG_ID17205, BINLOG_ID17206, BINLOG_ID17207, BINLOG_ID17208, BINLOG_ID17209, BINLOG_ID17210, BINLOG_ID17211, BINLOG_ID17212, BINLOG_ID17213, BINLOG_ID17214, BINLOG_ID17215, BINLOG_ID17216, BINLOG_ID17217, BINLOG_ID17218, BINLOG_ID17219, BINLOG_ID17220, BINLOG_ID17221, BINLOG_ID17222, BINLOG_ID17223, BINLOG_ID17224, BINLOG_ID17225, BINLOG_ID17226, BINLOG_ID17227, BINLOG_ID17228, BINLOG_ID17229, BINLOG_ID17230, BINLOG_ID17231, BINLOG_ID17232, BINLOG_ID17233, BINLOG_ID17234, BINLOG_ID17235, BINLOG_ID17236, BINLOG_ID17237, BINLOG_ID17238, BINLOG_ID17239, BINLOG_ID17240, BINLOG_ID17241, BINLOG_ID17242, BINLOG_ID17243, BINLOG_ID17244, BINLOG_ID17245, BINLOG_ID17246, BINLOG_ID17247, BINLOG_ID17248, BINLOG_ID17249, BINLOG_ID17250, BINLOG_ID17251, BINLOG_ID17252, BINLOG_ID17253, BINLOG_ID17254, BINLOG_ID17255, BINLOG_ID17256, BINLOG_ID17257, BINLOG_ID17258, BINLOG_ID17259, BINLOG_ID17260, BINLOG_ID17261, BINLOG_ID17262, BINLOG_ID17263, BINLOG_ID17264, BINLOG_ID17265, BINLOG_ID17266, BINLOG_ID17267, BINLOG_ID17268, BINLOG_ID17269, BINLOG_ID17270, BINLOG_ID17271, BINLOG_ID17272, BINLOG_ID17273, BINLOG_ID17274, BINLOG_ID17275, BINLOG_ID17276, BINLOG_ID17277, BINLOG_ID17278, BINLOG_ID17279, BINLOG_ID17280, BINLOG_ID17281, BINLOG_ID17282, BINLOG_ID17283, BINLOG_ID17284, BINLOG_ID17285, BINLOG_ID17286, BINLOG_ID17287, BINLOG_ID17288, BINLOG_ID17289, BINLOG_ID17290, BINLOG_ID17291, BINLOG_ID17292, BINLOG_ID17293, BINLOG_ID17294, BINLOG_ID17295, BINLOG_ID17296, BINLOG_ID17297, BINLOG_ID17298, BINLOG_ID17299, BINLOG_ID17300, BINLOG_ID17301, BINLOG_ID17302, BINLOG_ID17303, BINLOG_ID17304, BINLOG_ID17305, BINLOG_ID17306, BINLOG_ID17307, BINLOG_ID17308, BINLOG_ID17309, BINLOG_ID17310, BINLOG_ID17311, BINLOG_ID17312, BINLOG_ID17313, BINLOG_ID17314, BINLOG_ID17315, BINLOG_ID17316, BINLOG_ID17317, BINLOG_ID17318, BINLOG_ID17319, BINLOG_ID17320, BINLOG_ID17321, BINLOG_ID17322, BINLOG_ID17323, BINLOG_ID17324, BINLOG_ID17325, BINLOG_ID17326, BINLOG_ID17327, BINLOG_ID17328, BINLOG_ID17329, BINLOG_ID17330, BINLOG_ID17331, BINLOG_ID17332, BINLOG_ID17333, BINLOG_ID17334, BINLOG_ID17335, BINLOG_ID17336, BINLOG_ID17337, BINLOG_ID17338, BINLOG_ID17339, BINLOG_ID17340, BINLOG_ID17341, BINLOG_ID17342, BINLOG_ID17343, BINLOG_ID17344, BINLOG_ID17345, BINLOG_ID17346, BINLOG_ID17347, BINLOG_ID17348, BINLOG_ID17349, BINLOG_ID17350, BINLOG_ID17351, BINLOG_ID17352, BINLOG_ID17353, BINLOG_ID17354, BINLOG_ID17355, BINLOG_ID17356, BINLOG_ID17357, BINLOG_ID17358, BINLOG_ID17359, BINLOG_ID17360, BINLOG_ID17361, BINLOG_ID17362, BINLOG_ID17363, BINLOG_ID17364, BINLOG_ID17365, BINLOG_ID17366, BINLOG_ID17367, BINLOG_ID17368, BINLOG_ID17369, BINLOG_ID17370, BINLOG_ID17371, BINLOG_ID17372, BINLOG_ID17373, BINLOG_ID17374, BINLOG_ID17375, BINLOG_ID17376 }; #ifdef HITLS_BSL_LOG int32_t ReturnErrorNumberProcess(int32_t err, uint32_t logId, const void *logStr); #define RETURN_ERROR_NUMBER_PROCESS(err, logId, logStr) ReturnErrorNumberProcess(err, logId, LOG_STR(logStr)) #else #define RETURN_ERROR_NUMBER_PROCESS(err, logId, logStr) (err) #endif /* HITLS_BSL_LOG */ #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
tls/include/tls_binlog_id.h
C
unknown
41,126
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef TLS_CONFIG_H #define TLS_CONFIG_H #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "hitls_cert_type.h" #include "hitls_cert.h" #include "hitls_debug.h" #include "hitls_config.h" #include "hitls_session.h" #include "hitls_psk.h" #include "hitls_security.h" #include "hitls_sni.h" #include "hitls_alpn.h" #include "hitls_cookie.h" #include "sal_atomic.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "crypt_eal_provider.h" #endif #ifdef __cplusplus extern "C" { #endif /** * @ingroup config * @brief Certificate management context */ typedef struct CertMgrCtxInner CERT_MgrCtx; typedef struct TlsSessionManager TLS_SessionMgr; /** * @ingroup config * @brief DTLS 1.0 */ #define HITLS_VERSION_DTLS10 0xfeffu #define HITLS_TICKET_KEY_NAME_SIZE 16u #define HITLS_TICKET_KEY_SIZE 32u #define HITLS_TICKET_IV_SIZE 16u /* the default number of tickets of TLS1.3 server is 2 */ #define HITLS_TLS13_TICKET_NUM_DEFAULT 2u #define HITLS_MAX_EMPTY_RECORDS 32 #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT #define HITLS_MAX_SEND_FRAGMENT_DEFAULT 16384 #endif /* max cert list is 100k */ #define HITLS_MAX_CERT_LIST_DEFAULT (1024 * 100) /** * @brief Group information */ typedef struct { char *name; // group name int32_t paraId; // parameter id CRYPT_PKEY_ParaId int32_t algId; // algorithm id CRYPT_PKEY_AlgId int32_t secBits; // security bits uint16_t groupId; // iana group id, HITLS_NamedGroup uint32_t pubkeyLen; // public key length(CH keyshare / SH keyshare) uint32_t sharedkeyLen; // shared key length uint32_t ciphertextLen; // ciphertext length(SH keyshare) uint32_t versionBits; // TLS_VERSION_MASK bool isKem; // true: KEM, false: KEX } TLS_GroupInfo; /** * @brief Signature scheme information */ typedef struct { char *name; uint16_t signatureScheme; // HITLS_SignHashAlgo, IANA specified int32_t keyType; // HITLS_CERT_KeyType int32_t paraId; // CRYPT_PKEY_ParaId int32_t signHashAlgId; // combined sign hash algorithm id int32_t signAlgId; // CRYPT_PKEY_AlgId int32_t hashAlgId; // CRYPT_MD_AlgId int32_t secBits; // security bits uint32_t certVersionBits; // TLS_VERSION_MASK uint32_t chainVersionBits; // TLS_VERSION_MASK } TLS_SigSchemeInfo; #ifdef HITLS_TLS_FEATURE_PROVIDER /** * @brief TLS capability data */ typedef struct { HITLS_Config *config; CRYPT_EAL_ProvMgrCtx *provMgrCtx; } TLS_CapabilityData; #define TLS_CAPABILITY_LIST_MALLOC_SIZE 10 #endif typedef struct CustomExtMethods HITLS_CustomExts; /** * @brief TLS Global Configuration */ typedef struct TlsConfig { BSL_SAL_RefCount references; /* reference count */ HITLS_Lib_Ctx *libCtx; /* library context */ const char *attrName; /* attrName */ #ifdef HITLS_TLS_FEATURE_PROVIDER TLS_GroupInfo *groupInfo; uint32_t groupInfolen; uint32_t groupInfoSize; TLS_SigSchemeInfo *sigSchemeInfo; uint32_t sigSchemeInfolen; uint32_t sigSchemeInfoSize; #endif uint32_t version; /* supported proto version */ uint32_t originVersionMask; /* the original supported proto version mask */ uint16_t minVersion; /* min supported proto version */ uint16_t maxVersion; /* max supported proto version */ uint32_t modeSupport; /* support mode */ uint16_t *tls13CipherSuites; /* tls13 cipher suite */ uint32_t tls13cipherSuitesSize; uint16_t *cipherSuites; /* cipher suite */ uint32_t cipherSuitesSize; uint8_t *pointFormats; /* ec point format */ uint32_t pointFormatsSize; /* According to RFC 8446 4.2.7, before TLS 1.3 is ec curves; TLS 1.3: supported groups for the key exchange */ uint16_t *groups; uint32_t groupsSize; uint16_t *signAlgorithms; /* signature algorithm */ uint32_t signAlgorithmsSize; uint8_t *alpnList; /* application layer protocols list */ uint32_t alpnListSize; /* bytes of alpn, excluding the tail 0 byte */ HITLS_SecurityCb securityCb; /* Security callback */ void *securityExData; /* Security ex data */ int32_t securityLevel; /* Security level */ uint8_t *serverName; /* server name */ uint32_t serverNameSize; /* server name size */ int32_t readAhead; /* need read more data into user buffer, nonzero indicates yes, otherwise no */ uint32_t emptyRecordsNum; /* the max number of empty records can be received */ /* TLS1.2 psk */ uint8_t *pskIdentityHint; /* psk identity hint */ uint32_t hintSize; HITLS_PskClientCb pskClientCb; /* psk client callback */ HITLS_PskServerCb pskServerCb; /* psk server callback */ /* TLS1.3 psk */ HITLS_PskFindSessionCb pskFindSessionCb; /* TLS1.3 PSK server callback */ HITLS_PskUseSessionCb pskUseSessionCb; /* TLS1.3 PSK client callback */ HITLS_DtlsTimerCb dtlsTimerCb; /* DTLS get the timeout callback */ uint32_t dtlsPostHsTimeoutVal; /* DTLS over UDP completed handshake timeout */ HITLS_CRYPT_Key *dhTmp; /* Temporary DH key set by the user */ HITLS_DhTmpCb dhTmpCb; /* Temporary ECDH key set by the user */ HITLS_InfoCb infoCb; /* information indicator callback */ HITLS_MsgCb msgCb; /* message callback function cb for observing all SSL/TLS protocol messages */ void *msgArg; /* set argument arg to the callback function */ HITLS_RecordPaddingCb recordPaddingCb; /* the callback to specify the padding for TLS 1.3 records */ void *recordPaddingArg; /* assign a value arg that is passed to the callback */ uint32_t keyExchMode; /* TLS1.3 psk exchange mode */ uint32_t maxCertList; /* the maximum size allowed for the peer's certificate chain */ HITLS_TrustedCAList *caList; /* the list of CAs sent to the peer */ CERT_MgrCtx *certMgrCtx; /* certificate management context */ uint32_t sessionIdCtxSize; /* the size of sessionId context */ uint8_t sessionIdCtx[HITLS_SESSION_ID_CTX_MAX_SIZE]; /* the sessionId context */ uint32_t ticketNums; /* TLS1.3 ticket number */ uint16_t maxSendFragment; /* max send fragment to restrict the amount of plaintext bytes in any record */ uint32_t recInbufferSize; /* Rec inbuffer inital size */ TLS_SessionMgr *sessMgr; /* session management */ void *userData; /* user data */ HITLS_ConfigUserDataFreeCb userDataFreeCb; bool needCheckKeyUsage; /* whether to check keyusage, default on */ bool needCheckPmsVersion; /* whether to verify the version in premastersecret */ bool isSupportRenegotiation; /* support renegotiation */ bool allowClientRenegotiate; /* allow a renegotiation initiated by the client */ bool allowLegacyRenegotiate; /* whether to abort handshake when server doesn't support SecRenegotiation */ bool isResumptionOnRenego; /* supports session resume during renegotiation */ bool isSupportDhAuto; /* the DH parameter to be automatically selected */ /* Certificate Verification Mode */ bool isSupportClientVerify; /* Enable dual-ended authentication. only for server */ bool isSupportNoClientCert; /* Authentication Passed When Client Sends Empty Certificate. only for server */ bool isSupportPostHandshakeAuth; /* TLS1.3 support post handshake auth. for server and client */ bool isSupportVerifyNone; /* The handshake will be continued regardless of the verification result. for server and client */ bool isSupportClientOnceVerify; /* only request a client certificate once during the connection. only for server */ bool isQuietShutdown; /* is support the quiet shutdown mode */ bool isEncryptThenMac; /* is EncryptThenMac on */ bool isFlightTransmitEnable; /* sending of handshake information in one flighttransmit */ bool isSupportExtendMasterSecret; /* is support extended master secret */ bool isSupportSessionTicket; /* is support session ticket */ bool isSupportServerPreference; /* server cipher suites can be preferentially selected */ /* DTLS */ #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) bool isSupportDtlsCookieExchange; /* is dtls support cookie exchange */ #endif /** * Configurations in the HITLS_Ctx are classified into private configuration and global configuration. * The following parameters directly reference the global configuration in tls. * Private configuration: ctx->config.tlsConfig * The global configuration: ctx->globalConfig * Modifying the globalConfig will affects all associated HITLS_Ctx */ HITLS_AlpnSelectCb alpnSelectCb; /* alpn callback */ void *alpnUserData; /* the user data for alpn callback */ void *sniArg; /* the args for servername callback */ HITLS_SniDealCb sniDealCb; /* server name callback function */ #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB HITLS_ClientHelloCb clientHelloCb; /* ClientHello callback */ void *clientHelloCbArg; /* the args for ClientHello callback */ #endif /* HITLS_TLS_FEATURE_CLIENT_HELLO_CB */ #ifdef HITLS_TLS_PROTO_DTLS12 HITLS_AppGenCookieCb appGenCookieCb; HITLS_AppVerifyCookieCb appVerifyCookieCb; #endif HITLS_NewSessionCb newSessionCb; /* negotiates to generate a session */ HITLS_KeyLogCb keyLogCb; /* the key log callback */ bool isKeepPeerCert; /* whether to save the peer certificate */ HITLS_CustomExts *customExts; bool isMiddleBoxCompat; /* whether to support middlebox compatibility */ } TLS_Config; #define LIBCTX_FROM_CONFIG(config) ((config == NULL) ? NULL : (config)->libCtx) #define ATTRIBUTE_FROM_CONFIG(config) ((config == NULL) ? NULL : (config)->attrName) #ifdef __cplusplus } #endif #endif // TLS_CONFIG_H
2302_82127028/openHiTLS-examples_1508
tls/include/tls_config.h
C
unknown
11,164
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_H #define REC_H #include <stdbool.h> #include <stdint.h> #include "hitls_build.h" #include "hitls_crypt_type.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif #define DTLS_MIN_MTU 256 /* Minimum MTU setting size */ #define REC_MAX_PLAIN_LENGTH 16384 /* Maximum plain length */ /* TLS13 Maximum MAC address padding */ #define REC_MAX_TLS13_ENCRYPTED_OVERHEAD 256u /* TLS13 Maximum ciphertext length */ #define REC_MAX_TLS13_ENCRYPTED_LEN (REC_MAX_PLAIN_LENGTH + REC_MAX_TLS13_ENCRYPTED_OVERHEAD) #define REC_MASTER_SECRET_LEN 48 #define REC_RANDOM_LEN 32 #define RECORD_HEADER 0x100 #define RECORD_INNER_CONTENT_TYPE 0x101 /** * record type */ typedef enum { REC_TYPE_CHANGE_CIPHER_SPEC = 20, REC_TYPE_ALERT = 21, REC_TYPE_HANDSHAKE = 22, REC_TYPE_APP = 23, REC_TYPE_UNKNOWN = 255 } REC_Type; /** * SecurityParameters, used to generate keys and initialize the connect state */ typedef struct { bool isClient; /* Connection Endpoint */ bool isClientTrafficSecret; /* TrafficSecret type */ HITLS_HashAlgo prfAlg; /* prf_algorithm */ HITLS_MacAlgo macAlg; /* mac algorithm */ HITLS_CipherAlgo cipherAlg; /* symmetric encryption algorithm */ HITLS_CipherType cipherType; /* encryption algorithm type */ /* key length */ uint8_t fixedIvLength; /* iv length. In TLS1.2 AEAD algorithm is the implicit IV length */ uint8_t encKeyLen; /* Length of the symmetric key */ uint8_t macKeyLen; /* MAC key length: If the AEAD algorithm is used, the MAC key length is 0 */ uint8_t blockLength; /* If the block length is not zero, the alignment should be handled. */ uint8_t recordIvLength; /* The explicit IV needs to be sent to the peer */ uint8_t macLen; /* MAC length. For AEAD, it is the mark length */ uint8_t masterSecret[MAX_DIGEST_SIZE]; /* tls1.2 master key. TLS1.3 carries the TrafficSecret */ uint8_t clientRandom[REC_RANDOM_LEN]; /* Client random number */ uint8_t serverRandom[REC_RANDOM_LEN]; /* service random number */ } REC_SecParameters; /** * @ingroup record * @brief Record initialization * * @param ctx [IN] TLS object * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * */ int32_t REC_Init(TLS_Ctx *ctx); /** * @ingroup record * @brief record deinitialize * * @param ctx [IN] TLS object */ void REC_DeInit(TLS_Ctx *ctx); /** * @ingroup record * @brief Check whether data exists in the read buffer of the reocrd * * @param ctx [IN] TLS object * @return whether data exists in the read buffer */ bool REC_ReadHasPending(const TLS_Ctx *ctx); /** * @ingroup record * @brief Reads a message in the unit of a record. Data is read from the uio of the CTX to the data pointer * * @attention recordType indicates the expected record type (app or handshake) * readLen indicates the length of read data. The maximum length is REC_MAX_PLAIN_LENGTH (16384) * @param ctx [IN] TLS object * @param recordType [IN] Expected record type(app or handshake) * @param data [OUT] Read buffer * @param readLen [OUT] Length of the read data * @param num [IN] The size of read buffer, which must be greater than or equal to the maximum size of the record * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION,Invalid null pointer * @retval HITLS_REC_ERR_BUFFER_NOT_ENOUGH The buffer space is insufficient * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY indicates that the buffer is empty and needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG An unexpected message is received and needs to be processed * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t REC_Read(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num); /** * @ingroup record * @brief Write a record in the unit of record * * @attention If the value of num exceeds the maximum length of the record, return error * * @param ctx [IN] TLS object * @param recordType [IN] record type * @param data [IN] Write data * @param num [IN] Attempt to write num bytes of plaintext data * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_REC_ERR_BUFFER_NOT_ENOUGH The buffer space is insufficient * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_REC_PMTU_TOO_SMALL The PMTU is too small * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy * @retval HITLS_REC_ERR_TOO_BIG_LENGTH The length of the plaintext data written by the upper layer exceeds the * maximum length of the plaintext data that can be written by a single record * @retval HITLS_REC_ERR_NOT_SUPPORT_CIPHER The key algorithm is not supported * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num); /** * @ingroup record * @brief Activate the expired write state. This API is invoked in the retransmission scenario * * @attention Reservation Interface * @param ctx [IN] TLS object * */ void REC_ActiveOutdatedWriteState(TLS_Ctx *ctx); /** * @ingroup record * @brief Disable the expired write status. This API is invoked in the retransmission scenario * * @attention Reservation Interface * @param ctx [IN] TLS object * */ void REC_DeActiveOutdatedWriteState(TLS_Ctx *ctx); /** * @ingroup record * @brief Initialize the pending state * * @param ctx [IN] TLS object * @param param [IN] Security parameter * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * */ int32_t REC_InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param); /** * @ingroup record * @brief Activate the pending state, switch the pending state to the current state * * @attention ctx cannot be empty * @param ctx [IN] TLS object * @param isOut [IN] Indicates whether is the output type * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * */ int32_t REC_ActivePendingState(TLS_Ctx *ctx, bool isOut); /** * @brief Calculate the mtu * * @param ctx [IN] TLS_Ctx context * * @retval HITLS_SUCCESS * @retval ITLS_UIO_FAIL The uio ctrl failed */ int32_t REC_QueryMtu(TLS_Ctx *ctx); /** * @brief Obtain the maximum writable plaintext length of a single record * * @param ctx [IN] TLS_Ctx context * @param len [OUT] Maximum length of the plaintext * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_REC_PMTU_TOO_SMALL The PMTU is too small */ int32_t REC_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len); /** * @brief Obtain the maximum writable plaintext according to mtu * * @param ctx [IN] TLS_Ctx context * @param len [OUT] Maximum length of the plaintext * * @retval HITLS_SUCCESS * @retval HITLS_UIO_IO_TYPE_ERROR Not UDP uio * @retval HITLS_REC_PMTU_TOO_SMALL The PMTU is too small */ int32_t REC_GetMaxDataMtu(const TLS_Ctx *ctx, uint32_t *len); /** * @ingroup record * @brief TLS13 Initialize the pending state * * @param ctx [IN] TLS object * @param param [IN] Security parameter * @param isOut [IN] Indicates whether is the output type * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL Memory allocated failed * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * */ int32_t REC_TLS13InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param, bool isOut); /** * @ingroup record * @brief Retransmit a record * * @param recCtx [IN] Record context * @param recordType [IN] record type * @param data [IN] data * @param dataLen [IN] data length */ int32_t REC_RetransmitListAppend(REC_Ctx *recCtx, REC_Type recordType, const uint8_t *data, uint32_t dataLen); /** * @ingroup record * @brief Clean the retransmit list * * @param recCtx [IN] Record context */ void REC_RetransmitListClean(REC_Ctx *recCtx); /** * @ingroup record * @brief Flush the retransmit list * * @param ctx [IN] TLS object * @retval HITLS_SUCCESS */ int32_t REC_RetransmitListFlush(TLS_Ctx *ctx); REC_Type REC_GetUnexpectedMsgType(TLS_Ctx *ctx); bool REC_HaveReadSuiteInfo(const TLS_Ctx *ctx); /** * @ingroup app * @brief Obtain the length of the remaining readable app messages in the current record. * * @param ctx [IN] TLS object * @return Length of the remaining readable app message */ uint32_t APP_GetReadPendingBytes(const TLS_Ctx *ctx); int32_t REC_RecOutBufReSet(TLS_Ctx *ctx); /** * @ingroup record * @brief Flush the buffer uio * * @param ctx [IN] TLS object * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_IO_BUSY uio busy * @retval HITLS_REC_ERR_IO_EXCEPTION uio error */ int32_t REC_FlightTransmit(TLS_Ctx *ctx); /** * @brief Obtain the out buffer remaining size * * @param ctx [IN] TLS_Ctx context * * @retval the out buffer remaining size */ uint32_t REC_GetOutBufPendingSize(const TLS_Ctx *ctx); /** * @brief Flush the record out buffer * * @param ctx [IN] TLS_Ctx context * * @retval HITLS_SUCCESS Out buffer is empty or flush success * @retval HITLS_REC_NORMAL_IO_BUSY Out buffer is not empty, but the IO operation is busy */ int32_t REC_OutBufFlush(TLS_Ctx *ctx); #ifdef __cplusplus } #endif #endif /* REC_H */
2302_82127028/openHiTLS-examples_1508
tls/record/include/rec.h
C
unknown
10,296
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_error.h" #include "tls.h" int32_t CovertRecordAlertToReturnValue(ALERT_Description description) { switch (description) { case ALERT_PROTOCOL_VERSION: return HITLS_REC_INVALID_PROTOCOL_VERSION; case ALERT_BAD_RECORD_MAC: return HITLS_REC_BAD_RECORD_MAC; case ALERT_DECODE_ERROR: return HITLS_REC_DECODE_ERROR; case ALERT_RECORD_OVERFLOW: return HITLS_REC_RECORD_OVERFLOW; case ALERT_UNEXPECTED_MESSAGE: return HITLS_REC_ERR_RECV_UNEXPECTED_MSG; default: return HITLS_REC_INVLAID_RECORD; } } int32_t RecordSendAlertMsg(TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { /* RFC6347 4.1.2.7. Handling Invalid Records: We choose to discard invalid dtls record message and do not generate alerts. */ if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } else { ctx->method.sendAlert(ctx, level, description); return CovertRecordAlertToReturnValue(description); } }
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_alert.c
C
unknown
1,667
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_ALERT_H #define REC_ALERT_H #include <stdint.h> #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief record Send an alert and determine whether to discard invalid records * based on RFC6347 4.1.2.7. Handling Invalid Records * * @param ctx [IN] tls Context * @param level [IN] Alert level * @param description [IN] alert Description * * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY Discarding message * @retval Other invalid message error codes, such as HITLS_REC_INVLAID_RECORD and HITLS_REC_INVALID_PROTOCOL_VERSION */ int32_t RecordSendAlertMsg(TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_alert.h
C
unknown
1,239
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) #include "rec_anti_replay.h" #define REC_SLID_WINDOW_SIZE 64 void RecAntiReplayReset(RecSlidWindow *w) { w->top = 0; w->window = 0; return; } bool RecAntiReplayCheck(const RecSlidWindow *w, uint64_t seq) { if (seq > w->top) { return false; } uint64_t bit = w->top - seq; if (bit >= REC_SLID_WINDOW_SIZE) { /* The sequence number must be smaller than or equal to the minimum value of the sliding window */ return true; } /* return true: The sequence number is equal to a certain value in the sliding window */ return (w->window & ((uint64_t)1 << bit)) != 0; } void RecAntiReplayUpdate(RecSlidWindow *w, uint64_t seq) { /* If the sequence number is too small, the flag bit is not updated */ if ((seq + REC_SLID_WINDOW_SIZE) <= w->top) { return; } /* If the sequence number is less than or equal to top, update the flag */ if (seq <= w->top) { uint64_t bit = w->top - seq; w->window |= (uint64_t)1 << bit; return; } /* If the sequence number is greater than top, update the maximum sliding window size */ uint64_t bit = seq - w->top; w->top = seq; if (bit >= REC_SLID_WINDOW_SIZE) { /* If the number exceeds the current number too much, all previous flags are cleared and the maximum value is * updated */ w->window = 1; } else { w->window <<= bit; w->window |= 1; } return; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_anti_replay.c
C
unknown
2,161
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_ANTI_REPLAY_H #define REC_ANTI_REPLAY_H #include <stdint.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif /** * Anti-replay check function: * Use uint64_t variable to store flag bit,When receive a message, set the flag of corresponding sequence number to 1 * The least significant bit of the variable stores the maximum sequence number of the sliding window top, * when the top updates, shift the sliding window to the left * If a duplicate message or a message whose sequence number is smaller than the minimum sliding window value * is received, discard it * * window: 64 bits Range: [top-63, top) * 1. Initial state: * top - 63 top * | - - - - - - | * 2. hen the top + 2 message is received: * top - 61 top + 2 * | - - - - - - | */ typedef struct { uint64_t top; /* Stores the current maximum sequence number */ uint64_t window; /* Sliding window for storing flag bits */ } RecSlidWindow; /** * @brief Reset of the anti-replay module * The invoker must ensure that the input parameter is not empty * * @param w [IN] Sliding window */ void RecAntiReplayReset(RecSlidWindow *w); /** * @brief Anti-Replay Check * The invoker must ensure that the input parameter is not empty * * @param w [IN] Sliding window * @param seq [IN] Sequence number to be checked * * @retval true The sequence number is duplicate * @retval false The sequence number is not duplicate */ bool RecAntiReplayCheck(const RecSlidWindow *w, uint64_t seq); /** * @brief Update the window * This function can be invoked only after the anti-replay check is passed * Ensure that the input parameter is not empty by the invoker * * @param w [IN] Sliding window. The input parameter correctness is ensured externally * @param seq [IN] Sequence number of the window to be updated */ void RecAntiReplayUpdate(RecSlidWindow *w, uint64_t seq); #ifdef __cplusplus } #endif #endif /* REC_ANTI_REPLAY_H */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_anti_replay.h
C
unknown
2,612
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #include "securec.h" #include "bsl_sal.h" #include "bsl_list.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "hitls_error.h" #include "tls.h" #include "record.h" #include "rec_buf.h" RecBuf *RecBufNew(uint32_t bufSize) { RecBuf *buf = (RecBuf *)BSL_SAL_Calloc(1, sizeof(RecBuf)); if (buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17210, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } buf->buf = (uint8_t *)BSL_SAL_Calloc(1, bufSize); if (buf->buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17211, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_SAL_FREE(buf); return NULL; } buf->isHoldBuffer = true; buf->bufSize = bufSize; return buf; } int32_t RecBufResize(RecBuf *recBuf, uint32_t size) { if (recBuf == NULL || recBuf->bufSize == size || recBuf->end - recBuf->start > size) { return HITLS_SUCCESS; } uint8_t *newBuf = BSL_SAL_Calloc(size, sizeof(uint8_t)); if (newBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17212, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(newBuf, size, &recBuf->buf[recBuf->start], recBuf->end - recBuf->start); recBuf->end = recBuf->end - recBuf->start; recBuf->start = 0; BSL_SAL_FREE(recBuf->buf); recBuf->buf = newBuf; recBuf->bufSize = size; return HITLS_SUCCESS; } void RecBufFree(RecBuf *buf) { if (buf != NULL) { if (buf->isHoldBuffer) { BSL_SAL_FREE(buf->buf); } BSL_SAL_FREE(buf); } return; } void RecBufClean(RecBuf *buf) { buf->start = 0; buf->end = 0; return; } RecBufList *RecBufListNew(void) { return BSL_LIST_New(sizeof(RecBuf)); } void RecBufListFree(RecBufList *bufList) { BSL_LIST_FREE(bufList, (void(*)(void*))RecBufFree); } int32_t RecBufListDereference(RecBufList *bufList) { RecBuf *recBuf = (RecBuf *)BSL_LIST_GET_FIRST(bufList); while (recBuf != NULL) { if (!recBuf->isHoldBuffer) { uint8_t *buf = (uint8_t *)BSL_SAL_Dump(recBuf->buf, recBuf->bufSize); if (buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17215, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } recBuf->buf = buf; recBuf->isHoldBuffer = true; } recBuf = (RecBuf *)BSL_LIST_GET_NEXT(bufList); } return HITLS_SUCCESS; } bool RecBufListEmpty(RecBufList *bufList) { return BSL_LIST_GET_FIRST(bufList) == NULL; } int32_t RecBufListGetBuffer(RecBufList *bufList, uint8_t *buf, uint32_t bufLen, uint32_t *getLen, bool isPeek) { RecBuf *recBuf = (RecBuf *)BSL_LIST_GET_FIRST(bufList); if (recBuf == NULL || recBuf->buf == NULL) { *getLen = 0; return HITLS_SUCCESS; } uint32_t remain = recBuf->end - recBuf->start; uint32_t copyLen = (remain > bufLen) ? bufLen : remain; if (copyLen == 0) { if (recBuf->start == recBuf->end) { BSL_LIST_DeleteCurrent(bufList, (void(*)(void*))RecBufFree); } *getLen = 0; return HITLS_SUCCESS; } uint8_t *startBuf = &recBuf->buf[recBuf->start]; int32_t ret = memcpy_s(buf, bufLen, startBuf, copyLen); if (ret != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16242, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecBufListGetBuffer memcpy_s failed; buf may be nullptr", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } if (!isPeek) { recBuf->start += copyLen; } *getLen = copyLen; if (recBuf->start == recBuf->end) { BSL_LIST_DeleteCurrent(bufList, (void(*)(void*))RecBufFree); } return HITLS_SUCCESS; } int32_t RecBufListAddBuffer(RecBufList *bufList, RecBuf *buf) { RecBuf *newBuf = BSL_SAL_Calloc(1U, sizeof(RecBuf)); if (newBuf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17216, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(newBuf, sizeof(RecBuf), buf, sizeof(RecBuf)); if (BSL_LIST_AddElement(bufList, newBuf, BSL_LIST_POS_END) != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17217, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "AddElement fail", 0, 0, 0, 0); BSL_SAL_FREE(newBuf); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; }
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_buf.c
C
unknown
5,374
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_BUF_H #define REC_BUF_H #include <stdint.h> #include "bsl_list.h" #ifdef __cplusplus extern "C" { #endif typedef struct { uint8_t *buf; uint32_t bufSize; uint32_t start; uint32_t end; uint32_t singleRecStart; uint32_t singleRecEnd; bool isHoldBuffer; } RecBuf; typedef struct BslList RecBufList; /** * @brief Allocate buffer * * @param bufSize [IN] buffer size * * @return RecBuf Buffer handle */ RecBuf *RecBufNew(uint32_t bufSize); /** * @brief Release the buffer * * @param buf [IN] Buffer handle. The buffer is released by the invoker */ void RecBufFree(RecBuf *buf); /** * @brief Release the data in buffer * * @param buf [IN] Buffer handle */ void RecBufClean(RecBuf *buf); RecBufList *RecBufListNew(void); void RecBufListFree(RecBufList *bufList); int32_t RecBufListDereference(RecBufList *bufList); bool RecBufListEmpty(RecBufList *bufList); int32_t RecBufListGetBuffer(RecBufList *bufList, uint8_t *buf, uint32_t bufLen, uint32_t *getLen, bool isPeek); int32_t RecBufListAddBuffer(RecBufList *bufList, RecBuf *buf); int32_t RecBufResize(RecBuf *recBuf, uint32_t size); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_buf.h
C
unknown
1,740
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <string.h> #include "securec.h" #include "hitls_build.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "crypt.h" #include "rec_alert.h" #include "rec_crypto.h" #include "rec_conn.h" #define KEY_EXPANSION_LABEL "key expansion" #ifdef HITLS_TLS_SUITE_CIPHER_CBC #define CBC_MAC_HEADER_LEN 13U #endif RecConnState *RecConnStateNew(void) { RecConnState *state = (RecConnState *)BSL_SAL_Calloc(1, sizeof(RecConnState)); if (state == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15382, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record conn:malloc fail.", 0, 0, 0, 0); return NULL; } return state; } void RecConnStateFree(RecConnState *state) { if (state == NULL) { return; } if (state->suiteInfo != NULL) { #ifdef HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES SAL_CRYPT_HmacFree(state->suiteInfo->macCtx); state->suiteInfo->macCtx = NULL; #endif SAL_CRYPT_CipherFree(state->suiteInfo->ctx); state->suiteInfo->ctx = NULL; } /* Clear sensitive information */ BSL_SAL_CleanseData(state->suiteInfo, sizeof(RecConnSuitInfo)); BSL_SAL_FREE(state->suiteInfo); BSL_SAL_FREE(state); return; } uint64_t RecConnGetSeqNum(const RecConnState *state) { return state->seq; } void RecConnSetSeqNum(RecConnState *state, uint64_t seq) { state->seq = seq; } #ifdef HITLS_TLS_PROTO_DTLS12 uint16_t RecConnGetEpoch(const RecConnState *state) { return state->epoch; } void RecConnSetEpoch(RecConnState *state, uint16_t epoch) { state->epoch = epoch; } #endif int32_t RecConnStateSetCipherInfo(RecConnState *state, RecConnSuitInfo *suitInfo) { if (state->suiteInfo != NULL) { SAL_CRYPT_CipherFree(state->suiteInfo->ctx); state->suiteInfo->ctx = NULL; #ifdef HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES SAL_CRYPT_HmacFree(state->suiteInfo->macCtx); state->suiteInfo->macCtx = NULL; #endif } /* Clear sensitive information */ BSL_SAL_CleanseData(state->suiteInfo, sizeof(RecConnSuitInfo)); // Ensure that no memory leak occurs BSL_SAL_FREE(state->suiteInfo); state->suiteInfo = (RecConnSuitInfo *)BSL_SAL_Malloc(sizeof(RecConnSuitInfo)); if (state->suiteInfo == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15383, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record conn: malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(state->suiteInfo, sizeof(RecConnSuitInfo), suitInfo, sizeof(RecConnSuitInfo)); return HITLS_SUCCESS; } #ifdef HITLS_TLS_SUITE_CIPHER_CBC uint32_t RecGetHashAlgoFromMACAlgo(HITLS_MacAlgo macAlgo) { switch (macAlgo) { case HITLS_MAC_1: return HITLS_HASH_SHA1; case HITLS_MAC_256: return HITLS_HASH_SHA_256; case HITLS_MAC_224: return HITLS_HASH_SHA_224; case HITLS_MAC_384: return HITLS_HASH_SHA_384; case HITLS_MAC_512: return HITLS_HASH_SHA_512; #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_MAC_SM3: return HITLS_HASH_SM3; #endif default: BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15388, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CBC encrypt error: unsupport MAC algorithm = %u.", macAlgo, 0, 0, 0); break; } return HITLS_HASH_BUTT; } int32_t RecConnGenerateMac(HITLS_Lib_Ctx *libCtx, const char *attrName, RecConnSuitInfo *suiteInfo, const REC_TextInput *plainMsg, uint8_t *mac, uint32_t *macLen) { int32_t ret = HITLS_SUCCESS; uint8_t header[CBC_MAC_HEADER_LEN] = {0}; uint32_t offset = 0; if (memcpy_s(header, CBC_MAC_HEADER_LEN, plainMsg->seq, REC_CONN_SEQ_SIZE) != EOK) { // sequence or epoch + seq return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID17228, "memcpy fail"); } offset += REC_CONN_SEQ_SIZE; header[offset] = plainMsg->type; // The eighth byte is the record type offset++; BSL_Uint16ToByte(plainMsg->version, &header[offset]); // The 9th and 10th bytes are version numbers offset += sizeof(uint16_t); BSL_Uint16ToByte((uint16_t)plainMsg->textLen, &header[offset]); // The 11th and 12th bytes are the data length HITLS_HashAlgo hashAlgo = RecGetHashAlgoFromMACAlgo(suiteInfo->macAlg); if (hashAlgo == HITLS_HASH_BUTT) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_REC_ERR_GENERATE_MAC, BINLOG_ID17229, "RecGetHashAlgoFromMACAlgo fail"); } if (suiteInfo->macCtx == NULL) { suiteInfo->macCtx = SAL_CRYPT_HmacInit(libCtx, attrName, hashAlgo, suiteInfo->macKey, suiteInfo->macKeyLen); ret = suiteInfo->macCtx == NULL ? HITLS_REC_ERR_GENERATE_MAC : HITLS_SUCCESS; } else { ret = SAL_CRYPT_HmacReInit(suiteInfo->macCtx); } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_GENERATE_MAC); return RETURN_ERROR_NUMBER_PROCESS(HITLS_REC_ERR_GENERATE_MAC, BINLOG_ID15389, "SAL_CRYPT_HmacInit fail"); } ret = SAL_CRYPT_HmacUpdate(suiteInfo->macCtx, header, CBC_MAC_HEADER_LEN); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17230, "HmacUpdate fail"); } ret = SAL_CRYPT_HmacUpdate(suiteInfo->macCtx, plainMsg->text, plainMsg->textLen); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17231, "HmacUpdate fail"); } ret = SAL_CRYPT_HmacFinal(suiteInfo->macCtx, mac, macLen); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17232, "HmacFinal fail"); } return HITLS_SUCCESS; } void RecConnInitGenerateMacInput(const REC_TextInput *in, const uint8_t *text, uint32_t textLen, REC_TextInput *out) { out->version = in->version; out->negotiatedVersion = in->negotiatedVersion; #ifdef HITLS_TLS_FEATURE_ETM out->isEncryptThenMac = in->isEncryptThenMac; #endif out->type = in->type; out->text = text; out->textLen = textLen; for (uint32_t i = 0u; i < REC_CONN_SEQ_SIZE; i++) { out->seq[i] = in->seq[i]; } } int32_t RecConnCheckMac(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, const REC_TextInput *cryptMsg, const uint8_t *text, uint32_t textLen) { REC_TextInput input = {0}; uint8_t mac[MAX_DIGEST_SIZE] = {0}; uint32_t macLen = MAX_DIGEST_SIZE; RecConnInitGenerateMacInput(cryptMsg, text, textLen - suiteInfo->macLen, &input); int32_t ret = RecConnGenerateMac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), suiteInfo, &input, mac, &macLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17233, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnGenerateMac fail.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); } if (macLen != suiteInfo->macLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15929, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: macLen = %u, required len = %u.", macLen, suiteInfo->macLen, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } if (memcmp(&text[textLen - suiteInfo->macLen], mac, macLen) != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15942, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: MAC check failed.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_SUITE_CIPHER_CBC */ int32_t RecConnEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { return RecGetCryptoFuncs(state->suiteInfo)->encryt(ctx, state, plainMsg, cipherText, cipherTextLen); } int32_t RecConnDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { const RecCryptoFunc *funcs = RecGetCryptoFuncs(state->suiteInfo); uint32_t ciphertextLen = funcs->calCiphertextLen(ctx, state->suiteInfo, 0, true); // The length of the record body to be decrypted must be greater than or equal to ciphertextLen if (cryptMsg->textLen < ciphertextLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15403, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnDecrypt Failed: record body length to be decrypted is %u, lower bound of ciphertext len is %u", cryptMsg->textLen, ciphertextLen, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return funcs->decrypt(ctx, state, cryptMsg, data, dataLen); } static void PackSuitInfo(RecConnSuitInfo *suitInfo, const REC_SecParameters *param) { suitInfo->macAlg = param->macAlg; suitInfo->cipherAlg = param->cipherAlg; suitInfo->cipherType = param->cipherType; suitInfo->fixedIvLength = param->fixedIvLength; suitInfo->encKeyLen = param->encKeyLen; suitInfo->macKeyLen = param->macKeyLen; suitInfo->blockLength = param->blockLength; suitInfo->recordIvLength = param->recordIvLength; suitInfo->macLen = param->macLen; return; } static void RecConnCalcWriteKey(const REC_SecParameters *param, uint8_t *keyBuf, uint32_t keyBufLen, RecConnSuitInfo *client, RecConnSuitInfo *server) { if (keyBufLen == 0) { return; } uint32_t offset = 0; uint32_t totalOffset = 2 * param->macKeyLen + 2 * param->encKeyLen + 2 * param->fixedIvLength; if (keyBufLen < totalOffset) { return; } if (param->macKeyLen > 0u) { if (memcpy_s(client->macKey, sizeof(client->macKey), keyBuf, param->macKeyLen) != EOK) { return; } offset += param->macKeyLen; if (memcpy_s(server->macKey, sizeof(server->macKey), keyBuf + offset, param->macKeyLen) != EOK) { return; } offset += param->macKeyLen; } if (param->encKeyLen > 0u) { if (memcpy_s(client->key, sizeof(client->key), keyBuf + offset, param->encKeyLen) != EOK) { return; } offset += param->encKeyLen; if (memcpy_s(server->key, sizeof(server->key), keyBuf + offset, param->encKeyLen) != EOK) { return; } offset += param->encKeyLen; } if (param->fixedIvLength > 0u) { if (memcpy_s(client->iv, sizeof(client->iv), keyBuf + offset, param->fixedIvLength) != EOK) { return; } offset += param->fixedIvLength; if (memcpy_s(server->iv, sizeof(server->iv), keyBuf + offset, param->fixedIvLength) != EOK) { return; } } PackSuitInfo(client, param); PackSuitInfo(server, param); } int32_t RecConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *client, RecConnSuitInfo *server) { /** Calculate the key length: 2MAC, 2key, 2IV */ uint32_t keyLen = ((uint32_t)param->macKeyLen * 2) + ((uint32_t)param->encKeyLen * 2) + ((uint32_t)param->fixedIvLength * 2); if (keyLen == 0u || param->macKeyLen > sizeof(client->macKey) || param->encKeyLen > sizeof(client->key) || param->fixedIvLength > sizeof(client->iv)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_NOT_SUPPORT_CIPHER); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15943, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record Key: not support--length is invalid.", 0, 0, 0, 0); return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } /* Based on RFC5246 6.3 key_block = PRF(SecurityParameters.master_secret, "key expansion", SecurityParameters.server_random + SecurityParameters.client_random); */ CRYPT_KeyDeriveParameters keyDeriveParam = {0}; keyDeriveParam.hashAlgo = param->prfAlg; keyDeriveParam.secret = param->masterSecret; keyDeriveParam.secretLen = REC_MASTER_SECRET_LEN; keyDeriveParam.label = (const uint8_t *)KEY_EXPANSION_LABEL; keyDeriveParam.labelLen = strlen(KEY_EXPANSION_LABEL); keyDeriveParam.libCtx = libCtx; keyDeriveParam.attrName = attrName; uint8_t randomValue[REC_RANDOM_LEN * 2]; /** Random value of the replication server */ (void)memcpy_s(randomValue, sizeof(randomValue), param->serverRandom, REC_RANDOM_LEN); /** Random value of the replication client */ (void)memcpy_s(&randomValue[REC_RANDOM_LEN], sizeof(randomValue) - REC_RANDOM_LEN, param->clientRandom, REC_RANDOM_LEN); keyDeriveParam.seed = randomValue; // Total length of 2 random numbers keyDeriveParam.seedLen = REC_RANDOM_LEN * 2; /** Maximum key length: 2MAC, 2key, 2IV */ uint8_t keyBuf[REC_MAX_KEY_BLOCK_LEN]; int32_t ret = SAL_CRYPT_PRF(&keyDeriveParam, keyBuf, keyLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15944, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record Key:generate fail.", 0, 0, 0, 0); return ret; } RecConnCalcWriteKey(param, keyBuf, REC_MAX_KEY_BLOCK_LEN, client, server); BSL_SAL_CleanseData(keyBuf, sizeof(keyBuf)); return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t RecTLS13CalcWriteKey(CRYPT_KeyDeriveParameters *deriveInfo, uint8_t *key, uint32_t keyLen) { uint8_t label[] = "key"; deriveInfo->label = label; deriveInfo->labelLen = sizeof(label) - 1; return SAL_CRYPT_HkdfExpandLabel(deriveInfo, key, keyLen); } int32_t RecTLS13CalcWriteIv(CRYPT_KeyDeriveParameters *deriveInfo, uint8_t *iv, uint32_t ivLen) { uint8_t label[] = "iv"; deriveInfo->label = label; deriveInfo->labelLen = sizeof(label) - 1; return SAL_CRYPT_HkdfExpandLabel(deriveInfo, iv, ivLen); } int32_t RecTLS13ConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *suitInfo) { const uint8_t *secret = (const uint8_t *)param->masterSecret; uint32_t secretLen = SAL_CRYPT_DigestSize(param->prfAlg); if (secretLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17234, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DigestSize err", 0, 0, 0, 0); return HITLS_CRYPT_ERR_DIGEST; } uint32_t keyLen = param->encKeyLen; uint32_t ivLen = param->fixedIvLength; if (secretLen > sizeof(param->masterSecret) || keyLen > sizeof(suitInfo->key) || ivLen > sizeof(suitInfo->iv)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_NOT_SUPPORT_CIPHER); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15408, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "length is invalid.", 0, 0, 0, 0); return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } CRYPT_KeyDeriveParameters deriveInfo = {0}; deriveInfo.hashAlgo = param->prfAlg; deriveInfo.secret = secret; deriveInfo.secretLen = secretLen; deriveInfo.libCtx = libCtx; deriveInfo.attrName = attrName; int32_t ret = RecTLS13CalcWriteKey(&deriveInfo, suitInfo->key, keyLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17235, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcWriteKey fail", 0, 0, 0, 0); return ret; } ret = RecTLS13CalcWriteIv(&deriveInfo, suitInfo->iv, ivLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17236, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CalcWriteIv fail", 0, 0, 0, 0); return ret; } PackSuitInfo(suitInfo, param); return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_conn.c
C
unknown
16,301
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_CONN_H #define REC_CONN_H #include <stdint.h> #include <stddef.h> #include "rec.h" #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) #include "rec_anti_replay.h" #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ #ifdef __cplusplus extern "C" { #endif #define REC_MAX_MAC_KEY_LEN 64 #define REC_MAX_KEY_LENGTH 64 #define REC_MAX_IV_LENGTH 16 #define REC_MAX_KEY_BLOCK_LEN (REC_MAX_MAC_KEY_LEN * 2 + REC_MAX_KEY_LENGTH * 2 + REC_MAX_IV_LENGTH * 2) #define MAX_SHA1_SIZE 20 #define MAX_MD5_SIZE 16 #define REC_CONN_SEQ_SIZE 8u /* Sequence number size */ /** * Cipher suite information, which is required for local encryption and decryption * For details, see RFC5246 6.1 */ typedef struct { HITLS_MacAlgo macAlg; /* MAC algorithm */ HITLS_CipherAlgo cipherAlg; /* symmetric encryption algorithm */ HITLS_CipherType cipherType; /* encryption algorithm type */ HITLS_Cipher_Ctx *ctx; /* cipher context handle, only for record layer encryption and decryption */ HITLS_HMAC_Ctx *macCtx; /* mac context handle, only for record layer mac */ uint8_t macKey[REC_MAX_MAC_KEY_LEN]; uint8_t key[REC_MAX_KEY_LENGTH]; uint8_t iv[REC_MAX_IV_LENGTH]; bool isExportIV; /* Used by the TTO feature. The IV does not need to be randomly generated during CBC encryption If it is set by user */ /* key length */ uint8_t macKeyLen; /* Length of the MAC key. The length of the MAC key is 0 in AEAD algorithm */ uint8_t encKeyLen; /* Length of the symmetric key */ uint8_t fixedIvLength; /* iv length. It is the implicit IV length in AEAD algorithm */ /* result length */ uint8_t blockLength; /* If the block length is not zero, the alignment should be handled */ uint8_t recordIvLength; /* The explicit IV needs to be sent to the peer */ uint8_t macLen; /* Add the length of the MAC. Or the tag length in AEAD */ } RecConnSuitInfo; /* connection state */ typedef struct { RecConnSuitInfo *suiteInfo; /* Cipher suite information */ uint64_t seq; /* tls: 8 byte sequence number or dtls: 6 byte seq */ bool isWrapped; /* tls: Check whether the sequence number is wrapped */ uint16_t epoch; /* dtls: 2 byte epoch */ #if defined(HITLS_BSL_UIO_UDP) uint16_t reserve; /* Four-byte alignment is reserved */ RecSlidWindow window; /* dtls record sliding window (for anti-replay) */ #endif } RecConnState; /* see TLSPlaintext structure definition in rfc */ typedef struct { uint8_t type; // ccs(20), alert(21), hs(22), app data(23), (255) #ifdef HITLS_TLS_FEATURE_ETM bool isEncryptThenMac; #endif uint8_t reverse[2]; uint16_t version; uint16_t negotiatedVersion; uint8_t seq[REC_CONN_SEQ_SIZE]; /* 1. tls: sequence number 2.dtls: epoch + sequence */ uint32_t textLen; const uint8_t *text; // fragment } REC_TextInput; /** * @brief Initialize RecConnState */ RecConnState *RecConnStateNew(void); /** * @brief Release RecConnState */ void RecConnStateFree(RecConnState *state); /** * @brief Obtain the Sequence number * * @param state [IN] Connection state * * @retval Sequence number */ uint64_t RecConnGetSeqNum(const RecConnState *state); /** * @brief Set the Sequence number * * @param state [IN] Connection state * @param seq [IN] Sequence number * * @retval Sequence number */ void RecConnSetSeqNum(RecConnState *state, uint64_t seq); #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Obtain the epoch * * @attention state can not be null pointer * * @param state [IN] Connection state * * @retval epoch */ uint16_t RecConnGetEpoch(const RecConnState *state); /** * @brief Set epoch * * @attention state can not be null pointer * @param state [IN] Connection state * @param epoch [IN] epoch * */ void RecConnSetEpoch(RecConnState *state, uint16_t epoch); #endif /** * @brief Set the key information * * @param state [IN] Connection state * @param suitInfo [IN] Ciphersuite information * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval HITLS_MEMALLOC_FAIL Memory allocated failed */ int32_t RecConnStateSetCipherInfo(RecConnState *state, RecConnSuitInfo *suitInfo); /** * @brief Encrypt the record payload * * @param ctx [IN] tls Context * @param state RecState context * @param plainMsg [IN] Input data before encryption * @param cipherText [OUT] Encrypted content * @param cipherTextLen [IN] Length after encryption * * @retval HITLS_SUCCESS * @retval HITLS_MEMCPY_FAIL Memory copy failed * @retval HITLS_REC_ERR_NOT_SUPPORT_CIPHER The key algorithm is not supported * @retval HITLS_REC_ERR_ENCRYPT Encryption failed * @see SAL_CRYPT_Encrypt */ int32_t RecConnEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen); /** * @brief Decrypt the record payload * * @param ctx [IN] tls Context * @param state RecState context * @param cryptMsg [IN] Content to be decrypted * @param data [OUT] Decrypted data * @param dataLen [IN/OUT] IN: length of data OUT: length after decryption * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_NOT_SUPPORT_CIPHER The key algorithm is not supported * @retval HITLS_MEMCPY_FAIL Memory copy failed */ int32_t RecConnDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen); /** * @brief Key generation * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param param [IN] Security parameter * @param client [OUT] Client key material * @param server [OUT] Server key material * * @retval HITLS_SUCCESS * @retval HITLS_INTERNAL_EXCEPTION Invalid null pointer * @retval Reference SAL_CRYPT_PRF */ int32_t RecConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *client, RecConnSuitInfo *server); /** * @brief TLS1.3 Key generation * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param param [IN] Security parameter * @param suitInfo [OUT] key material * * @retval HITLS_SUCCESS * @retval HITLS_UNREGISTERED_CALLBACK Unregistered callback * @retval HITLS_CRYPT_ERR_DIGEST hash calculation failed * @retval HITLS_CRYPT_ERR_HKDF_EXPAND HKDF-Expand calculation fails * */ int32_t RecTLS13ConnKeyBlockGen(HITLS_Lib_Ctx *libCtx, const char *attrName, const REC_SecParameters *param, RecConnSuitInfo *suitInfo); /* * @brief check the mac * * @param ctx [IN] tls Context * @param suiteInfo [IN] ciphersuiteInfo * @param cryptMsg [IN] text info * @param text [IN] fragment * @param textLen [IN] fragment len * @retval HITLS_SUCCESS * @retval Reference hitls_error.h */ int32_t RecConnCheckMac(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, const REC_TextInput *cryptMsg, const uint8_t *text, uint32_t textLen); /* * @brief generate the mac * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param suiteInfo [IN] ciphersuiteInfo * @param plainMsg [IN] text info * @param mac [OUT] mac buffer * @param macLen [OUT] mac buffer len * @retval HITLS_SUCCESS * @retval Reference hitls_error.h */ int32_t RecConnGenerateMac(HITLS_Lib_Ctx *libCtx, const char *attrName, RecConnSuitInfo *suiteInfo, const REC_TextInput *plainMsg, uint8_t *mac, uint32_t *macLen); /* * @brief check the mac * * @param in [IN] plaintext info * @param text [IN] plaintext buf * @param textLen [IN] plaintext buf len * @param out [IN] mac info * @retval HITLS_SUCCESS * @retval Reference hitls_error.h */ void RecConnInitGenerateMacInput(const REC_TextInput *in, const uint8_t *text, uint32_t textLen, REC_TextInput *out); #ifdef HITLS_TLS_SUITE_CIPHER_CBC uint32_t RecGetHashAlgoFromMACAlgo(HITLS_MacAlgo macAlgo); #endif #ifdef __cplusplus } #endif #endif /* REC_CONN_H */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_conn.h
C
unknown
9,038
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <string.h> #include "securec.h" #include "hitls_build.h" #include "bsl_bytes.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #ifdef HITLS_TLS_SUITE_CIPHER_AEAD #include "rec_crypto_aead.h" #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC #include "rec_crypto_cbc.h" #endif #include "tls_binlog_id.h" #include "rec_conn.h" #include "rec_alert.h" #include "indicator.h" #include "hs.h" #include "hitls_error.h" #ifdef HITLS_TLS_PROTO_TLS13 /* 16384 + 1: RFC8446 5.4. Record Padding the full encoded TLSInnerPlaintext MUST NOT exceed 2^14 + 1 octets. */ #define MAX_PADDING_LEN 16385 /* * * @brief Obtain the content and record message types from the decrypted TLSInnerPlaintext. * After TLS1.3 decryption, the TLSInnerPlaintext structure is used. The padding needs to be removed and the actual message type needs to be obtained. * * struct { * opaque content[TLSPlaintext.length]; * ContentType type; * uint8 zeros[length_of_padding]; * } TLSInnerPlaintext; * * @param text [IN] Decrypted content (TLSInnerPlaintext) * @param textLen [OUT] Input (length of TLSInnerPlaintext) * Length of the output content * @param recType [OUT] Message body length * * @return HITLS_SUCCESS succeeded * HITLS_ALERT_FATAL Unexpected Message */ int32_t RecParseInnerPlaintext(TLS_Ctx *ctx, const uint8_t *text, uint32_t *textLen, uint8_t *recType) { /* The receiver decrypts and scans the field from the end to the beginning until it finds a non-zero octet. This * non-zero byte is the message type of record If no non-zero bytes are found, an unexpected alert needs to be sent * and the chain is terminated */ uint32_t len = *textLen; for (uint32_t i = len; i > 0; i--) { if (text[i - 1] != 0) { *recType = text[i - 1]; // When the value is the same as the rectype index, the value is the length of the content *textLen = i - 1; return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_RECV_UNEXPECTED_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15453, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Recved UNEXPECTED_MESSAGE.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } #endif /* HITLS_TLS_PROTO_TLS13 */ static int32_t DefaultDecryptPostProcess(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, REC_TextInput *encryptedMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)suiteInfo; (void)encryptedMsg; (void)data; (void)dataLen; #ifdef HITLS_TLS_PROTO_TLS13 /* If the version is tls1.3 and encryption is required, you need to create a TLSInnerPlaintext message */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13 && suiteInfo != NULL) { return RecParseInnerPlaintext(ctx, data, dataLen, &encryptedMsg->type); } #endif return HITLS_SUCCESS; } static int32_t DefaultEncryptPreProcess(TLS_Ctx *ctx, uint8_t recordType, const uint8_t *data, uint32_t plainLen, RecordPlaintext *recPlaintext) { #ifdef HITLS_TLS_PROTO_TLS (void)ctx, (void)data; recPlaintext->recordType = recordType; recPlaintext->plainLen = plainLen; recPlaintext->plainData = NULL; #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13 || ctx->recCtx->writeStates.currentState->suiteInfo == NULL) { return HITLS_SUCCESS; } recPlaintext->isTlsInnerPlaintext = true; /* Currently, the padding length is set to 0. If required, the padding length can be customized */ uint16_t recPaddingLength = 0; if (ctx->config.tlsConfig.recordPaddingCb != NULL) { recPaddingLength = (uint16_t)ctx->config.tlsConfig.recordPaddingCb(ctx, recordType, plainLen, ctx->config.tlsConfig.recordPaddingArg); } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate( 0, HS_GetVersion(ctx), RECORD_INNER_CONTENT_TYPE, &recordType, 1, ctx, ctx->config.tlsConfig.msgArg); #endif /* TlsInnerPlaintext see rfc 8446 section 5.2 */ /* tlsInnerPlaintext length = content length + record type length (1) + padding length */ uint32_t tlsInnerPlaintextLen = plainLen + sizeof(uint8_t) + recPaddingLength; if (tlsInnerPlaintextLen > MAX_PADDING_LEN) { BSL_ERR_PUSH_ERROR(HITLS_REC_RECORD_OVERFLOW); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15669, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Pack TlsInnerPlaintext length(%u) MUST NOT exceed 2^14 + 1 octets.", tlsInnerPlaintextLen, 0, 0, 0); return HITLS_REC_RECORD_OVERFLOW; } uint8_t *tlsInnerPlaintext = BSL_SAL_Calloc(1u, tlsInnerPlaintextLen); if (tlsInnerPlaintext == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID17253, "Calloc fail"); } if (memcpy_s(tlsInnerPlaintext, tlsInnerPlaintextLen, data, plainLen) != EOK) { BSL_SAL_FREE(tlsInnerPlaintext); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMCPY_FAIL, BINLOG_ID17254, "memcpy fail"); } tlsInnerPlaintext[plainLen] = recordType; /* Padding is calloc when the memory is applied for. Therefore, the number of buffs to be supplemented is 0. You do * not need to perform any operation */ recPlaintext->plainLen = tlsInnerPlaintextLen; recPlaintext->plainData = tlsInnerPlaintext; /* tls1.3 Hide the actual record type during encryption */ recPlaintext->recordType = (uint8_t)REC_TYPE_APP; #endif /* HITLS_TLS_PROTO_TLS13 */ return HITLS_SUCCESS; #else (void)ctx, (void)recordType, (void)data, (void)plainLen, (void)recPlaintext; return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; #endif /* HITLS_TLS_PROTO_TLS */ } static uint32_t PlainCalCiphertextLen(const TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t plantextLen, bool isRead) { (void)ctx; (void)suiteInfo; (void)isRead; return plantextLen; } static int32_t PlainCalPlantextBufLen(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plainLen) { (void)ctx; (void)suiteInfo; *offset = 0; *plainLen = ciphertextLen; return HITLS_SUCCESS; } static int32_t PlainDecrypt(TLS_Ctx *ctx, RecConnState *suiteInfo, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)suiteInfo; if (memcpy_s(data, *dataLen, cryptMsg->text, cryptMsg->textLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15404, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnDecrypt Failed: memcpy fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } // For empty ciphersuite case, the plaintext length is equal to ciphertext length *dataLen = cryptMsg->textLen; return HITLS_SUCCESS; } static int32_t PlainEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { (void)ctx; (void)state; if (memcpy_s(cipherText, cipherTextLen, plainMsg->text, plainMsg->textLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15926, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:memcpy fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } static int32_t UnsupoortDecrypt(TLS_Ctx *ctx, RecConnState *suiteInfo, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)suiteInfo; (void)cryptMsg; (void)data; (void)dataLen; return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } static int32_t UnsupoortEncrypt(TLS_Ctx *ctx, RecConnState *State, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { (void)ctx; (void)State; (void)plainMsg; (void)cipherText; (void)cipherTextLen; return HITLS_REC_ERR_NOT_SUPPORT_CIPHER; } const RecCryptoFunc *RecGetCryptoFuncs(const RecConnSuitInfo *suiteInfo) { static RecCryptoFunc cryptoFuncPlain = { PlainCalCiphertextLen, PlainCalPlantextBufLen, PlainDecrypt, DefaultDecryptPostProcess, PlainEncrypt, DefaultEncryptPreProcess }; if (suiteInfo == NULL) { return &cryptoFuncPlain; } switch (suiteInfo->cipherType) { #ifdef HITLS_TLS_SUITE_CIPHER_AEAD case HITLS_AEAD_CIPHER: return RecGetAeadCryptoFuncs(DefaultDecryptPostProcess, DefaultEncryptPreProcess); #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC case HITLS_CBC_CIPHER: return RecGetCbcCryptoFuncs(DefaultDecryptPostProcess, DefaultEncryptPreProcess); #endif default: break; } BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_NOT_SUPPORT_CIPHER); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16240, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Internal error, unsupport cipher.", 0, 0, 0, 0); static RecCryptoFunc cryptoFuncUnsupport = { PlainCalCiphertextLen, PlainCalPlantextBufLen, UnsupoortDecrypt, DefaultDecryptPostProcess, UnsupoortEncrypt, DefaultEncryptPreProcess }; return &cryptoFuncUnsupport; }
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_crypto.c
C
unknown
9,838
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_CRYPT_H #define REC_CRYPT_H #include "hitls_build.h" #include "hitls_error.h" #include "record.h" #include "rec_conn.h" #ifdef HITLS_TLS_PROTO_TLS typedef struct { REC_Type recordType; /* Protocol type */ uint32_t plainLen; /* message length */ uint8_t *plainData; /* message data */ #ifdef HITLS_TLS_PROTO_TLS13 /* Length of the tls1.3 padding content. Currently, the value is 0. The value can be used as required */ uint64_t recPaddingLength; #endif bool isTlsInnerPlaintext; /* Whether it is a TLSInnerPlaintext message for tls1.3 */ } RecordPlaintext; /* Record protocol data before encryption */ #else typedef struct DtlsRecordPlaintext RecordPlaintext; #endif typedef uint32_t (*CalCiphertextLenFunc)(const TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, uint32_t plantextLen, bool isRead); typedef int32_t (*CalPlantextBufLenFunc)(TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plaintextLen); typedef int32_t (*DecryptFunc)(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen); typedef int32_t (*EncryptFunc)(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen); typedef int32_t (*DecryptPostProcess)(TLS_Ctx *ctx, RecConnSuitInfo *suitInfo, REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen); typedef int32_t (*EncryptPreProcess)(TLS_Ctx *ctx, uint8_t recordType, const uint8_t *data, uint32_t plainLen, RecordPlaintext *recPlaintext); typedef struct { CalCiphertextLenFunc calCiphertextLen; CalPlantextBufLenFunc calPlantextBufLen; DecryptFunc decrypt; DecryptPostProcess decryptPostProcess; EncryptFunc encryt; EncryptPreProcess encryptPreProcess; } RecCryptoFunc; const RecCryptoFunc *RecGetCryptoFuncs(const RecConnSuitInfo *suiteInfo); #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_crypto.h
C
unknown
2,452
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <string.h> #include "hitls_build.h" #ifdef HITLS_TLS_SUITE_CIPHER_AEAD #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "crypt.h" #include "hitls_error.h" #include "record.h" #include "rec_alert.h" #include "rec_conn.h" #include "rec_crypto_aead.h" #define AEAD_AAD_TLS12_SIZE 13u /* TLS1.2 AEAD additional_data length */ #define AEAD_AAD_MAX_SIZE AEAD_AAD_TLS12_SIZE #define AEAD_NONCE_SIZE 12u /* The length of the AEAD nonce is fixed to 12 */ #define AEAD_NONCE_ZEROS_SIZE 4u /* The length of the AEAD nonce First 4 bytes */ #ifdef HITLS_TLS_PROTO_TLS13 #define AEAD_AAD_TLS13_SIZE 5u /* TLS1.3 AEAD additional_data length */ #endif static int32_t CleanSensitiveData(int32_t ret, uint8_t *nonce, uint8_t *aad, uint32_t outLen, uint32_t cipherLen) { BSL_SAL_CleanseData(nonce, AEAD_NONCE_SIZE); BSL_SAL_CleanseData(aad, AEAD_AAD_MAX_SIZE); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15480, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:encrypt record error.", NULL, NULL, NULL, NULL); return ret; } if (outLen != cipherLen) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15481, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:encrypt error. outLen:%u cipherLen:%u", outLen, cipherLen, NULL, NULL); return HITLS_REC_ERR_ENCRYPT; } return HITLS_SUCCESS; } static int32_t AeadGetNonce(const RecConnSuitInfo *suiteInfo, uint8_t *nonce, uint8_t nonceLen, const uint8_t *seq, uint8_t seqLen) { uint8_t fixedIvLength = suiteInfo->fixedIvLength; uint8_t recordIvLength = suiteInfo->recordIvLength; if ((fixedIvLength + recordIvLength) != nonceLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17239, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "nonceLen err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_AEAD_NONCE_PARAM); return HITLS_REC_ERR_AEAD_NONCE_PARAM; // The caller should ensure that the input is correct } if (recordIvLength == seqLen) { /* * According to the RFC5116 && RFC5288 AEAD_AES_128_GCM/AEAD_AES_256_GCM definition, the nonce length is fixed * to 12. 4 bytes + 8bytes(64 bits record sequence number, big endian) = 12 bytes 4 bytes the implicit part be * derived from iv. The first 4 bytes of the IV are obtained. */ (void)memcpy_s(nonce, nonceLen, suiteInfo->iv, fixedIvLength); (void)memcpy_s(&nonce[fixedIvLength], recordIvLength, seq, seqLen); return HITLS_SUCCESS; } else if (recordIvLength == 0) { /* * (same as defined in RFC7905 AEAD_CHACHA20_POLY1305) * The per-record nonce for the AEAD defined in RFC8446 5.3 * First 4 bytes (all 0s) + Last 8bytes(64 bits record sequence number, big endian) = 12 bytes * Perform XOR with the 12 bytes IV. The result is nonce. */ // First four bytes (all 0s) (void)memset_s(&nonce[0], nonceLen, 0, AEAD_NONCE_ZEROS_SIZE); // First 4 bytes (all 0s) + Last 8 bytes (64-bit record sequence number, big endian) (void)memcpy_s(&nonce[AEAD_NONCE_ZEROS_SIZE], nonceLen - AEAD_NONCE_ZEROS_SIZE, seq, seqLen); for (uint32_t i = 0; i < nonceLen; i++) { nonce[i] = nonce[i] ^ suiteInfo->iv[i]; } return HITLS_SUCCESS; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17240, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get nonce fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_AEAD_NONCE_PARAM); return HITLS_REC_ERR_AEAD_NONCE_PARAM; } static void AeadGetAad(uint8_t *aad, uint32_t *aadLen, const REC_TextInput *input, uint32_t plainDataLen) { #ifdef HITLS_TLS_PROTO_TLS13 /* TLS1.3 generation additional_data = TLSCiphertext.opaque_type || TLSCiphertext.legacy_record_version || TLSCiphertext.length */ if (input->negotiatedVersion == HITLS_VERSION_TLS13) { // The 0th byte is the record type aad[0] = input->type; uint32_t offset = 1; // The first and second bytes of indicate the version number BSL_Uint16ToByte(input->version, &aad[offset]); offset += sizeof(uint16_t); // The third and fourth bytes of indicate the data length BSL_Uint16ToByte((uint16_t)plainDataLen, &aad[offset]); *aadLen = AEAD_AAD_TLS13_SIZE; return; } #endif /* HITLS_TLS_PROTO_TLS13 */ /* non-TLS1.3 generation additional_data = seq_num + TLSCompressed.type + TLSCompressed.version + * TLSCompressed.length */ (void)memcpy_s(aad, AEAD_AAD_MAX_SIZE, input->seq, REC_CONN_SEQ_SIZE); uint32_t offset = REC_CONN_SEQ_SIZE; aad[offset] = input->type; // The eighth byte indicates the record type offset++; BSL_Uint16ToByte(input->version, &aad[offset]); // The ninth and tenth bytes indicate the version number. offset += sizeof(uint16_t); BSL_Uint16ToByte((uint16_t)plainDataLen, &aad[offset]); // The 11th and 12th bytse indicate the data length. *aadLen = AEAD_AAD_TLS12_SIZE; return; } static uint32_t AeadCalCiphertextLen(const TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t plantextLen, bool isRead) { (void)ctx; (void)isRead; return plantextLen + suiteInfo->macLen + suiteInfo->recordIvLength; } static int32_t AeadCalPlantextBufLen(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plainLen) { (void)ctx; *offset = suiteInfo->recordIvLength; uint32_t plantextLen = ciphertextLen - suiteInfo->macLen - suiteInfo->recordIvLength; if (plantextLen > ciphertextLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17241, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "plantextLen err", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } *plainLen = plantextLen; return HITLS_SUCCESS; } static int32_t AeadDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { RecConnSuitInfo *suiteInfo = state->suiteInfo; /** Initialize the encryption length offset */ uint32_t cipherOffset = 0u; HITLS_CipherParameters cipherParam = {0}; cipherParam.ctx = &suiteInfo->ctx; cipherParam.type = suiteInfo->cipherType; cipherParam.algo = suiteInfo->cipherAlg; cipherParam.key = (const uint8_t *)suiteInfo->key; cipherParam.keyLen = suiteInfo->encKeyLen; /** Read the explicit IV during AEAD decryption */ const uint8_t *recordIv; if (suiteInfo->recordIvLength > 0u) { recordIv = &cryptMsg->text[cipherOffset]; cipherOffset += REC_CONN_SEQ_SIZE; } else { // If no IV is displayed, use the serial number recordIv = cryptMsg->seq; } /** Calculate NONCE */ uint8_t nonce[AEAD_NONCE_SIZE] = {0}; int32_t ret = AeadGetNonce(suiteInfo, nonce, sizeof(nonce), recordIv, REC_CONN_SEQ_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15395, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record decrypt:get nonce failed.", 0, 0, 0, 0); return ret; } cipherParam.iv = nonce; cipherParam.ivLen = AEAD_NONCE_SIZE; /* Calculate additional_data */ uint8_t aad[AEAD_AAD_MAX_SIZE] = {0}; uint32_t aadLen = AEAD_AAD_MAX_SIZE; /* Definition of additional_data tls1.2 additional_data = seq_num + TLSCompressed.type + TLSCompressed.version + TLSCompressed.length; tls1.3 additional_data = TLSCiphertext.opaque_type || TLSCiphertext.legacy_record_version || TLSCiphertext.length diff: length */ uint32_t plainDataLen = cryptMsg->textLen; if (cryptMsg->negotiatedVersion != HITLS_VERSION_TLS13) { plainDataLen = cryptMsg->textLen - suiteInfo->recordIvLength - suiteInfo->macLen; } AeadGetAad(aad, &aadLen, cryptMsg, plainDataLen); cipherParam.aad = aad; cipherParam.aadLen = aadLen; /** Calculate the encryption length: GenericAEADCipher.content + aead tag */ uint32_t cipherLen = cryptMsg->textLen - cipherOffset; /** Decryption */ ret = SAL_CRYPT_Decrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, &cryptMsg->text[cipherOffset], cipherLen, data, dataLen); /* Clear sensitive information */ BSL_SAL_CleanseData(nonce, AEAD_NONCE_SIZE); BSL_SAL_CleanseData(aad, AEAD_AAD_MAX_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15396, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "decrypt record error. ret:%d", ret, 0, 0, 0); if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); return HITLS_REC_BAD_RECORD_MAC; } return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return HITLS_SUCCESS; } /** * @brief AEAD encryption * * @param state [IN] RecConnState Context * @param input [IN] Input data before encryption * @param cipherText [OUT] Encrypted content * @param cipherTextLen [IN] Length after encryption * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_INTERNAL_EXCEPTION: null pointer * @retval HITLS_MEMCPY_FAIL The copy fails. * @retval For details, see SAL_CRYPT_Encrypt. */ static int32_t AeadEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { /** Initialize the encryption length offset */ uint32_t cipherOffset = 0u; HITLS_CipherParameters cipherParam = {0}; cipherParam.ctx = &state->suiteInfo->ctx; cipherParam.type = state->suiteInfo->cipherType; cipherParam.algo = state->suiteInfo->cipherAlg; cipherParam.key = (const uint8_t *)state->suiteInfo->key; cipherParam.keyLen = state->suiteInfo->encKeyLen; /** During AEAD encryption, the sequence number is used as the explicit IV */ if (state->suiteInfo->recordIvLength > 0u) { if (memcpy_s(&cipherText[cipherOffset], cipherTextLen, plainMsg->seq, REC_CONN_SEQ_SIZE) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15384, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record encrypt:memcpy fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } cipherOffset += REC_CONN_SEQ_SIZE; } /** Calculate NONCE */ uint8_t nonce[AEAD_NONCE_SIZE] = {0}; int32_t ret = AeadGetNonce(state->suiteInfo, nonce, sizeof(nonce), plainMsg->seq, REC_CONN_SEQ_SIZE); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15385, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record encrypt:get nonce failed.", 0, 0, 0, 0); return ret; } cipherParam.iv = nonce; cipherParam.ivLen = AEAD_NONCE_SIZE; /* Calculate additional_data */ uint8_t aad[AEAD_AAD_MAX_SIZE]; uint32_t aadLen = AEAD_AAD_MAX_SIZE; uint32_t textLen = #ifdef HITLS_TLS_PROTO_TLS13 (plainMsg->negotiatedVersion == HITLS_VERSION_TLS13) ? cipherTextLen : #endif /* HITLS_TLS_PROTO_TLS13 */ plainMsg->textLen; AeadGetAad(aad, &aadLen, plainMsg, textLen); cipherParam.aad = aad; cipherParam.aadLen = aadLen; /** Calculate the encryption length */ uint32_t cipherLen = cipherTextLen - cipherOffset; uint32_t outLen = cipherLen; /** Encryption */ ret = SAL_CRYPT_Encrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, plainMsg->text, plainMsg->textLen, &cipherText[cipherOffset], &outLen); /* Clear sensitive information */ return CleanSensitiveData(ret, nonce, aad, outLen, cipherLen); } const RecCryptoFunc *RecGetAeadCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess) { static RecCryptoFunc cryptoFuncAead = { .calCiphertextLen = AeadCalCiphertextLen, .calPlantextBufLen = AeadCalPlantextBufLen, .decrypt = AeadDecrypt, .encryt = AeadEncrypt, }; cryptoFuncAead.decryptPostProcess = decryptPostProcess; cryptoFuncAead.encryptPreProcess = encryptPreProcess; return &cryptoFuncAead; } #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_crypto_aead.c
C
unknown
12,947
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_CRYPT_AEAD_H #define REC_CRYPT_AEAD_H #include "rec_crypto.h" const RecCryptoFunc *RecGetAeadCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess); #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_crypto_aead.h
C
unknown
744
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_TLS_SUITE_CIPHER_CBC #include "securec.h" #include "hitls_error.h" #include "bsl_err_internal.h" #include "bsl_log_internal.h" #include "tls_binlog_id.h" #include "bsl_bytes.h" #include "crypt.h" #include "rec_alert.h" #include "rec_conn.h" #include "record.h" #include "rec_crypto_cbc.h" #define CBC_PADDING_LEN_TAG_SIZE 1u #define HMAC_MAX_BLEN 144 uint8_t RecConnGetCbcPaddingLen(uint8_t blockLen, uint32_t plaintextLen) { if (blockLen == 0) { return 0; } uint8_t remainder = (plaintextLen + CBC_PADDING_LEN_TAG_SIZE) % blockLen; if (remainder == 0) { return 0; } return blockLen - remainder; } static uint32_t CbcCalCiphertextLen(const TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t plantextLen, bool isRead) { uint32_t ciphertextLen = plantextLen; ciphertextLen += suiteInfo->recordIvLength; bool isEncryptThenMac = isRead ? ctx->negotiatedInfo.isEncryptThenMacRead : ctx->negotiatedInfo.isEncryptThenMacWrite; if (isEncryptThenMac) { ciphertextLen += RecConnGetCbcPaddingLen(suiteInfo->blockLength, ciphertextLen) + CBC_PADDING_LEN_TAG_SIZE; ciphertextLen += suiteInfo->macLen; } else { ciphertextLen += suiteInfo->macLen; ciphertextLen += RecConnGetCbcPaddingLen(suiteInfo->blockLength, ciphertextLen) + CBC_PADDING_LEN_TAG_SIZE; } return ciphertextLen; } static int32_t CbcCalPlantextBufLen(TLS_Ctx *ctx, RecConnSuitInfo *suiteInfo, uint32_t ciphertextLen, uint32_t *offset, uint32_t *plainLen) { uint32_t plantextLen = ciphertextLen; *offset = suiteInfo->recordIvLength; plantextLen -= *offset; if (ctx->negotiatedInfo.isEncryptThenMacRead) { plantextLen -= suiteInfo->macLen; } if (plantextLen > ciphertextLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17242, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "plantextLen err", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } *plainLen = plantextLen; return HITLS_SUCCESS; } static void RecConnInitCipherParam(HITLS_CipherParameters *cipherParam, const RecConnState *state) { cipherParam->ctx = &state->suiteInfo->ctx; cipherParam->type = state->suiteInfo->cipherType; cipherParam->algo = state->suiteInfo->cipherAlg; cipherParam->key = state->suiteInfo->key; cipherParam->keyLen = state->suiteInfo->encKeyLen; cipherParam->iv = state->suiteInfo->iv; cipherParam->ivLen = state->suiteInfo->fixedIvLength; } static int32_t RecConnCbcCheckCryptMsg(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *cryptMsg, bool isEncryptThenMac) { uint8_t offset = 0; if (isEncryptThenMac) { offset = state->suiteInfo->macLen; } if ((state->suiteInfo->blockLength == 0) || ((cryptMsg->textLen - offset) % state->suiteInfo->blockLength != 0)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15397, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: block length = %u, cipher text length = %u.", state->suiteInfo->blockLength, cryptMsg->textLen, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } return HITLS_SUCCESS; } static int32_t RecConnCbcDecCheckPaddingEtM(TLS_Ctx *ctx, const REC_TextInput *cryptMsg, uint8_t *plain, uint32_t plainLen, uint32_t offset) { const RecConnState *state = ctx->recCtx->readStates.currentState; uint8_t padLen = plain[plainLen - 1]; if (cryptMsg->isEncryptThenMac && (plainLen < padLen + CBC_PADDING_LEN_TAG_SIZE)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15399, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: ciphertext len = %u, plaintext len = %u, mac len = %u, padding len = %u.", cryptMsg->textLen - offset - state->suiteInfo->macLen, plainLen, state->suiteInfo->macLen, padLen); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } for (uint32_t i = 1; i <= padLen; i++) { if (plain[plainLen - 1 - i] != padLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15400, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error: padding len = %u, %u-to-last padding data = %u.", padLen, i, plain[plainLen - 1 - i], 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } } return HITLS_SUCCESS; } static uint32_t GetHmacBLen(HITLS_MacAlgo macAlgo) { switch (macAlgo) { case HITLS_MAC_1: case HITLS_MAC_224: case HITLS_MAC_256: case HITLS_MAC_SM3: return 64; // Blen of upper hmac is 64. case HITLS_MAC_384: case HITLS_MAC_512: return 128; // Blen of upper hmac is 128. default: // should never be here. return 0; } } /** * a constant-time implemenation of HMAC to prevent side-channel attacks * reference: https://datatracker.ietf.org/doc/html/rfc2104#autoid-2 */ static int32_t ConstTimeHmac(RecConnSuitInfo *suiteInfo, HITLS_HASH_Ctx **hashCtx, uint32_t good, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t dataLen, uint8_t *mac, uint32_t *macLen) { HITLS_HASH_Ctx *obCtx = hashCtx[2]; uint32_t padLen = data[dataLen - 1]; padLen = Uint32ConstTimeSelect(good, padLen, 0); uint32_t plainLen = dataLen - (suiteInfo->macLen + padLen + 1); plainLen = Uint32ConstTimeSelect(good, plainLen, 0); uint32_t blen = GetHmacBLen(suiteInfo->macAlg); uint8_t ipad[HMAC_MAX_BLEN] = {0}; uint8_t opad[HMAC_MAX_BLEN * 2] = {0}; uint8_t key[HMAC_MAX_BLEN] = {0}; uint8_t ihash[MAX_DIGEST_SIZE] = {0}; uint32_t ihashLen = sizeof(ihash); (void)memcpy_s(key, sizeof(key), suiteInfo->macKey, suiteInfo->macKeyLen); for (uint32_t i = 0; i < blen; i++) { ipad[i] = key[i] ^ 0x36; opad[i] = key[i] ^ 0x5c; } // update K xor ipad (void)SAL_CRYPT_DigestUpdate(hashCtx[0], ipad, blen); // update the obscureHashCtx simultaneously (void)SAL_CRYPT_DigestUpdate(obCtx, ipad, blen); /** * constant-time update plaintext to resist lucky13 * ref: https://www.isg.rhul.ac.uk/tls/TLStiming.pdf */ uint8_t header[13] = {0}; // seq + record type uint32_t pos = 0; (void)memcpy_s(header, sizeof(header), cryptMsg->seq, REC_CONN_SEQ_SIZE); pos += REC_CONN_SEQ_SIZE; header[pos++] = cryptMsg->type; BSL_Uint16ToByte(cryptMsg->version, header + pos); pos += sizeof(uint16_t); BSL_Uint16ToByte((uint16_t)plainLen, header + pos); (void)SAL_CRYPT_DigestUpdate(hashCtx[0], header, sizeof(header)); (void)SAL_CRYPT_DigestUpdate(obCtx, header, sizeof(header)); uint32_t maxLen = dataLen - (suiteInfo->macLen + 1); maxLen = Uint32ConstTimeSelect(good, maxLen, dataLen); uint32_t flag = Uint32ConstTimeGt(maxLen, 256); // the value of 1 byte is up to 256 uint32_t minLen = Uint32ConstTimeSelect(flag, maxLen - 256, 0); (void)SAL_CRYPT_DigestUpdate(hashCtx[0], data, minLen); (void)SAL_CRYPT_DigestUpdate(obCtx, data, minLen); for (uint32_t i = minLen; i < maxLen; i++) { if (i < plainLen) { SAL_CRYPT_DigestUpdate(hashCtx[0], data + i, 1); } else { SAL_CRYPT_DigestUpdate(obCtx, data + i, 1); } } (void)SAL_CRYPT_DigestFinal(hashCtx[0], ihash, &ihashLen); (void)memcpy_s(opad + blen, MAX_DIGEST_SIZE, ihash, ihashLen); // update (K xor opad) + ihash (void)SAL_CRYPT_DigestUpdate(hashCtx[1], opad, blen + ihashLen); (void)SAL_CRYPT_DigestFinal(hashCtx[1], mac, macLen); BSL_SAL_CleanseData(ipad, sizeof(ipad)); BSL_SAL_CleanseData(opad, sizeof(opad)); BSL_SAL_CleanseData(key, sizeof(key)); return HITLS_SUCCESS; } static inline uint32_t ConstTimeSelectMemcmp(uint32_t good, uint8_t *a, uint8_t *b, uint32_t l) { uint8_t *t = (good == 0) ? b : a; return ConstTimeMemcmp(t, b, l); } static int32_t RecConnCbcDecMtECheckMacTls(TLS_Ctx *ctx, const REC_TextInput *cryptMsg, uint8_t *plain, uint32_t plainLen) { const RecConnState *state = ctx->recCtx->readStates.currentState; uint32_t hashAlg = RecGetHashAlgoFromMACAlgo(state->suiteInfo->macAlg); if (hashAlg == HITLS_HASH_BUTT) { return HITLS_CRYPT_ERR_HMAC; } HITLS_HASH_Ctx *ihashCtx = NULL; HITLS_HASH_Ctx *ohashCtx = NULL; HITLS_HASH_Ctx *obscureHashCtx = NULL; ihashCtx = SAL_CRYPT_DigestInit(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), hashAlg); ohashCtx = SAL_CRYPT_DigestCopy(ihashCtx); obscureHashCtx = SAL_CRYPT_DigestCopy(ihashCtx); if (ihashCtx == NULL || ohashCtx == NULL || obscureHashCtx == NULL) { SAL_CRYPT_DigestFree(ihashCtx); SAL_CRYPT_DigestFree(ohashCtx); SAL_CRYPT_DigestFree(obscureHashCtx); return HITLS_REC_ERR_GENERATE_MAC; } uint8_t mac[MAX_DIGEST_SIZE] = {0}; uint32_t macLen = sizeof(mac); uint8_t padLen = plain[plainLen - 1]; uint32_t good = Uint32ConstTimeGe(plainLen, state->suiteInfo->macLen + padLen + 1); // constant-time check padding bytes for (uint32_t i = 1; i <= 255; i++) { uint32_t mask = good & Uint32ConstTimeLe(i, padLen); good &= Uint32ConstTimeEqual(plain[plainLen - 1 - (i & mask)], padLen); } HITLS_HASH_Ctx *hashCtxs[3] = {ihashCtx, ohashCtx, obscureHashCtx}; ConstTimeHmac(state->suiteInfo, hashCtxs, good, cryptMsg, plain, plainLen, mac, &macLen); // check mac uint32_t retLen = Uint32ConstTimeSelect(good, padLen, 0); plainLen -= state->suiteInfo->macLen + retLen + 1; good &= ConstTimeSelectMemcmp(good, &plain[plainLen], mac, macLen); SAL_CRYPT_DigestFree(ihashCtx); SAL_CRYPT_DigestFree(ohashCtx); SAL_CRYPT_DigestFree(obscureHashCtx); return ~good; } static int32_t RecConnCbcDecryptByMacThenEncrypt(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { /* Check whether the ciphertext length is an integral multiple of the ciphertext block length */ int32_t ret = RecConnCbcCheckCryptMsg(ctx, state, cryptMsg, false); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17243, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcCheckCryptMsg fail", 0, 0, 0, 0); return ret; } /* Decryption start position */ uint32_t offset = 0; /* plaintext length */ uint32_t plaintextLen = *dataLen; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); /* In TLS1.1 and later versions, explicit iv is used as the first ciphertext block. Therefore, the first * ciphertext block does not need to be decrypted */ cipherParam.iv = cryptMsg->text; offset = state->suiteInfo->fixedIvLength; ret = SAL_CRYPT_Decrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, &cryptMsg->text[offset], cryptMsg->textLen - offset, data, &plaintextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15398, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } /* Check padding and padding length */ ret = RecConnCbcDecMtECheckMacTls(ctx, cryptMsg, data, plaintextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17244, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcDecMtECheckMacTls fail", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } *dataLen = plaintextLen - (state->suiteInfo->macLen + data[plaintextLen - 1] + CBC_PADDING_LEN_TAG_SIZE); return ret; } static int32_t RecConnCbcDecryptByEncryptThenMac(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { /* Check MAC */ int32_t ret = RecConnCheckMac(ctx, state->suiteInfo, cryptMsg, cryptMsg->text, cryptMsg->textLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17245, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "check mac fail", 0, 0, 0, 0); return ret; } /* Check whether the ciphertext length is an integral multiple of the ciphertext block length */ ret = RecConnCbcCheckCryptMsg(ctx, state, cryptMsg, true); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17246, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcCheckCryptMsg fail", 0, 0, 0, 0); return ret; } /* Decryption start position */ uint32_t offset = 0; /* plaintext length */ uint32_t plaintextLen = *dataLen; uint8_t macLen = state->suiteInfo->macLen; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); /* In TLS1.1 and later versions, explicit iv is used as the first ciphertext block. Therefore, the first * ciphertext block does not need to be decrypted */ cipherParam.iv = cryptMsg->text; offset = state->suiteInfo->fixedIvLength; ret = SAL_CRYPT_Decrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, &cryptMsg->text[offset], cryptMsg->textLen - offset - macLen, data, &plaintextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15915, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "record cbc mode decrypt error.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } /* Check padding and padding length */ uint8_t paddingLen = data[plaintextLen - 1]; ret = RecConnCbcDecCheckPaddingEtM(ctx, cryptMsg, data, plaintextLen, offset); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17247, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnCbcDecCheckPaddingEtM fail", 0, 0, 0, 0); return ret; } *dataLen = plaintextLen - paddingLen - CBC_PADDING_LEN_TAG_SIZE; return HITLS_SUCCESS; } static int32_t CbcDecrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { uint8_t *decryptData = data; uint32_t decryptDataLen = *dataLen; int32_t ret; if (ctx->negotiatedInfo.isEncryptThenMacRead) { ret = RecConnCbcDecryptByEncryptThenMac(ctx, state, cryptMsg, decryptData, &decryptDataLen); } else { ret = RecConnCbcDecryptByMacThenEncrypt(ctx, state, cryptMsg, decryptData, &decryptDataLen); } if (ret != HITLS_SUCCESS) { return ret; } *dataLen = decryptDataLen; return HITLS_SUCCESS; } static int32_t RecConnCopyIV(TLS_Ctx *ctx, const RecConnState *state, uint8_t *cipherText, uint32_t cipherTextLen) { if (!state->suiteInfo->isExportIV) { SAL_CRYPT_Rand(LIBCTX_FROM_CTX(ctx), state->suiteInfo->iv, state->suiteInfo->fixedIvLength); } /* The IV set by the user can only be used once */ state->suiteInfo->isExportIV = 0; if (memcpy_s(cipherText, cipherTextLen, state->suiteInfo->iv, state->suiteInfo->fixedIvLength) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15847, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: copy iv fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } /* Data that needs to be encrypted (do not fill MAC) */ static int32_t GenerateCbcPlainTextBeforeMac(const RecConnState *state, const REC_TextInput *plainMsg, uint32_t cipherTextLen, uint8_t *plainText, uint32_t *textLen) { /* fill content */ if (memcpy_s(plainText, cipherTextLen, plainMsg->text, plainMsg->textLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15392, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memcpy plainMsg fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } uint32_t plainTextLen = plainMsg->textLen; /* fill padding and padding length */ uint8_t paddingLen = RecConnGetCbcPaddingLen(state->suiteInfo->blockLength, plainTextLen); uint32_t count = paddingLen + CBC_PADDING_LEN_TAG_SIZE; if (memset_s(&plainText[plainTextLen], cipherTextLen - plainTextLen, paddingLen, count) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15904, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memset padding fail.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } plainTextLen += count; *textLen = plainTextLen; return HITLS_SUCCESS; } static int32_t PreparePlainText(const RecConnState *state, const REC_TextInput *plainMsg, uint32_t cipherTextLen, uint8_t **plainText, uint32_t *plainTextLen) { *plainText = BSL_SAL_Calloc(1u, cipherTextLen); if (*plainText == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15927, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: out of memory.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } int32_t ret = GenerateCbcPlainTextBeforeMac(state, plainMsg, cipherTextLen, *plainText, plainTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(*plainText); } return ret; } /* Data that needs to be encrypted (after filling the mac) */ static int32_t GenerateCbcPlainTextAfterMac(HITLS_Lib_Ctx *libCtx, const char *attrName, const RecConnState *state, const REC_TextInput *plainMsg, uint32_t cipherTextLen, uint8_t *plainText, uint32_t *textLen) { /* Fill content */ if (memcpy_s(plainText, cipherTextLen, plainMsg->text, plainMsg->textLen) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15898, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memcpy plainMsg fail.", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } uint32_t plainTextLen = plainMsg->textLen; /* Fill MAC */ uint32_t macLen = state->suiteInfo->macLen; REC_TextInput input = {0}; RecConnInitGenerateMacInput(plainMsg, plainMsg->text, plainMsg->textLen, &input); int32_t ret = RecConnGenerateMac(libCtx, attrName, state->suiteInfo, &input, &plainText[plainTextLen], &macLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17248, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnGenerateMac fail.", 0, 0, 0, 0); return ret; } plainTextLen += macLen; /* Fill padding and padding length */ uint8_t paddingLen = RecConnGetCbcPaddingLen(state->suiteInfo->blockLength, plainTextLen); uint32_t count = paddingLen + CBC_PADDING_LEN_TAG_SIZE; if (memset_s(&plainText[plainTextLen], cipherTextLen - plainTextLen, paddingLen, count) != EOK) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15393, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: memset padding fail.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } plainTextLen += count; *textLen = plainTextLen; return HITLS_SUCCESS; } static int32_t RecConnCbcEncryptThenMac(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { uint32_t offset = 0; uint8_t *plainText = NULL; uint32_t plainTextLen = 0; int32_t ret = PreparePlainText(state, plainMsg, cipherTextLen, &plainText, &plainTextLen); if (ret != HITLS_SUCCESS) { return ret; } ret = RecConnCopyIV(ctx, state, cipherText, cipherTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(plainText); return ret; } offset += state->suiteInfo->fixedIvLength; uint32_t macLen = state->suiteInfo->macLen; uint32_t encLen = cipherTextLen - offset - macLen; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); ret = SAL_CRYPT_Encrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, plainText, plainTextLen, &cipherText[offset], &encLen); BSL_SAL_FREE(plainText); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15848, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CBC encrypt record error.", 0, 0, 0, 0); return ret; } if (encLen != (cipherTextLen - offset - macLen)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15903, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encrypt record (length) error.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } /* fill MAC */ REC_TextInput input = {0}; RecConnInitGenerateMacInput(plainMsg, cipherText, cipherTextLen - macLen, &input); return RecConnGenerateMac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), state->suiteInfo, &input, &cipherText[offset + encLen], &macLen); } int32_t RecConnCbcMacThenEncrypt(TLS_Ctx *ctx, const RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { uint32_t plainTextLen = 0; uint8_t *plainText = BSL_SAL_Calloc(1u, cipherTextLen); if (plainText == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15390, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record CBC encrypt error: out of memory.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } int32_t ret = GenerateCbcPlainTextAfterMac(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), state, plainMsg, cipherTextLen, plainText, &plainTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(plainText); return ret; } uint32_t offset = 0; ret = RecConnCopyIV(ctx, state, cipherText, cipherTextLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(plainText); return ret; } offset += state->suiteInfo->fixedIvLength; uint32_t encLen = cipherTextLen - offset; HITLS_CipherParameters cipherParam = {0}; RecConnInitCipherParam(&cipherParam, state); ret = SAL_CRYPT_Encrypt(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &cipherParam, plainText, plainTextLen, &cipherText[offset], &encLen); BSL_SAL_FREE(plainText); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15391, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CBC encrypt record error.", 0, 0, 0, 0); return ret; } if (encLen != (cipherTextLen - offset)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_ENCRYPT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15922, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encrypt record (length) error.", 0, 0, 0, 0); return HITLS_REC_ERR_ENCRYPT; } return HITLS_SUCCESS; } static int32_t CbcEncrypt(TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *plainMsg, uint8_t *cipherText, uint32_t cipherTextLen) { if (plainMsg->isEncryptThenMac) { return RecConnCbcEncryptThenMac(ctx, state, plainMsg, cipherText, cipherTextLen); } return RecConnCbcMacThenEncrypt(ctx, state, plainMsg, cipherText, cipherTextLen); } const RecCryptoFunc *RecGetCbcCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess) { static RecCryptoFunc cryptoFuncCbc = { .calCiphertextLen = CbcCalCiphertextLen, .calPlantextBufLen = CbcCalPlantextBufLen, .decrypt = CbcDecrypt, .encryt = CbcEncrypt, }; cryptoFuncCbc.decryptPostProcess = decryptPostProcess; cryptoFuncCbc.encryptPreProcess = encryptPreProcess; return &cryptoFuncCbc; } #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_crypto_cbc.c
C
unknown
24,385
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_CRYPT_CBC_H #define REC_CRYPT_CBC_H #include "rec_crypto.h" const RecCryptoFunc *RecGetCbcCryptoFuncs(DecryptPostProcess decryptPostProcess, EncryptPreProcess encryptPreProcess); #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_crypto_cbc.h
C
unknown
742
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef RECORD_HEADER_H #define RECORD_HEADER_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define REC_TLS_RECORD_HEADER_LEN 5u #define REC_TLS_RECORD_LENGTH_OFFSET 3 #define REC_TLS_SN_MAX_VALUE (~((uint64_t)0)) /* TLS sequence number wrap Threshold */ #ifdef HITLS_TLS_PROTO_DTLS12 #define REC_IP_UDP_HEAD_SIZE 28 /* IP protocol header 20 + UDP header 8 */ #define REC_DTLS_RECORD_HEADER_LEN 13 #define REC_DTLS_RECORD_EPOCH_OFFSET 3 #define REC_DTLS_RECORD_LENGTH_OFFSET 11 /* DTLS sequence number cannot be greater than this value. Otherwise, it will wrapped */ #define REC_DTLS_SN_MAX_VALUE 0xFFFFFFFFFFFFllu #define REC_SEQ_GET(n) ((n) & 0x0000FFFFFFFFFFFFull) #define REC_EPOCH_GET(n) ((uint16_t)((n) >> 48)) #define REC_EPOCHSEQ_CAL(epoch, seq) (((uint64_t)(epoch) << 48) | (seq)) /* Epoch cannot be greater than this value. Otherwise, it will wrapped */ #define REC_EPOCH_MAX_VALUE 0xFFFFu #endif typedef struct { uint8_t type; uint8_t reverse[3]; /* Reserved, 4-byte aligned */ uint16_t version; uint16_t bodyLen; /* body length */ #ifdef HITLS_TLS_PROTO_DTLS12 uint64_t epochSeq; /* only for dtls */ #endif } RecHdr; #ifdef __cplusplus } #endif #endif /* RECORD_HEADER_H */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_header.h
C
unknown
1,825
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #include "securec.h" #include "bsl_sal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_config.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "rec_alert.h" #ifdef HITLS_TLS_PROTO_TLS13 #include "hs_common.h" #endif #include "tls_config.h" #include "record.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif #include "hs_ctx.h" #include "hs.h" #include "rec_crypto.h" #include "bsl_list.h" RecConnState *GetReadConnState(const TLS_Ctx *ctx) { /** Obtains the record structure. */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; return recordCtx->readStates.currentState; } static bool IsNeedtoRead(const TLS_Ctx *ctx, const RecBuf *inBuf) { (void)ctx; uint32_t headLen = REC_TLS_RECORD_HEADER_LEN; #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { headLen = REC_DTLS_RECORD_HEADER_LEN; } #endif uint32_t lengthOffset = headLen - sizeof(uint16_t); uint32_t remain = inBuf->end - inBuf->start; if (remain < headLen) { return true; } uint8_t *recordHeader = &inBuf->buf[inBuf->start]; uint32_t recordLen = BSL_ByteToUint16(&recordHeader[lengthOffset]); if (remain < headLen + recordLen) { return true; } return false; } bool REC_HaveReadSuiteInfo(const TLS_Ctx *ctx) { if (ctx == NULL || ctx->recCtx == NULL || ctx->recCtx->readStates.currentState == NULL) { return false; } return ctx->recCtx->readStates.currentState->suiteInfo != NULL; } static REC_Type RecCastUintToRecType(TLS_Ctx *ctx, uint8_t value) { (void)ctx; REC_Type type; /* Convert to the record type */ switch (value) { case 20u: type = REC_TYPE_CHANGE_CIPHER_SPEC; break; case 21u: type = REC_TYPE_ALERT; break; case 22u: type = REC_TYPE_HANDSHAKE; break; case 23u: type = REC_TYPE_APP; break; default: type = REC_TYPE_UNKNOWN; break; } #ifdef HITLS_TLS_PROTO_TLS13 RecConnState *state = GetReadConnState(ctx); if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13 && state->suiteInfo != NULL) { if (type != REC_TYPE_APP && type != REC_TYPE_ALERT && (type != REC_TYPE_CHANGE_CIPHER_SPEC || ctx->hsCtx == NULL)) { type = REC_TYPE_UNKNOWN; } } #endif /* HITLS_TLS_PROTO_TLS13 */ return type; } #define REC_GetMaxReadSize(ctx) REC_MAX_PLAIN_LENGTH static int32_t ProcessDecryptedRecord(TLS_Ctx *ctx, uint32_t dataLen, const REC_TextInput *encryptedMsg) { /* The TLSPlaintext.length MUST NOT exceed 2^14. An endpoint that receives a record that exceeds this length MUST terminate the connection with a record_overflow alert */ if (dataLen > REC_GetMaxReadSize(ctx)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16165, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TLSPlaintext.length exceeds 2^14", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } if (encryptedMsg->type != REC_TYPE_APP && dataLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16166, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } if (!IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && ctx->negotiatedInfo.version != HITLS_VERSION_TLS13 && ctx->method.isRecvCCS(ctx) && encryptedMsg->type != REC_TYPE_HANDSHAKE) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_REC_ERR_DATA_BETWEEN_CCS_AND_FINISHED; } return HITLS_SUCCESS; } static int32_t EmptyRecordProcess(TLS_Ctx *ctx, uint8_t type) { if (REC_HaveReadSuiteInfo(ctx)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17255, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encryptedMsg->textLen is 0", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } if (type == REC_TYPE_ALERT || type == REC_TYPE_APP) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17256, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "type err", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } ctx->recCtx->emptyRecordCnt += 1; if (ctx->recCtx->emptyRecordCnt > ctx->config.tlsConfig.emptyRecordsNum) { BSL_LOG_BINLOG_FIXLEN( BINLOG_ID16187, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get too many empty records", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } else { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } } static int32_t RecordDecrypt(TLS_Ctx *ctx, RecBuf *decryptBuf, REC_TextInput *encryptedMsg) { if (encryptedMsg->textLen == 0) { return EmptyRecordProcess(ctx, encryptedMsg->type); } else { ctx->recCtx->emptyRecordCnt = 0; } RecConnState *state = GetReadConnState(ctx); const RecCryptoFunc *funcs = RecGetCryptoFuncs(state->suiteInfo); uint32_t offset = 0; int32_t ret = HITLS_SUCCESS; uint32_t minBufLen = 0; ret = funcs->calPlantextBufLen(ctx, state->suiteInfo, encryptedMsg->textLen, &offset, &minBufLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16266, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Invalid record length %u", encryptedMsg->textLen, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_BAD_RECORD_MAC); } if ((minBufLen > decryptBuf->bufSize || ctx->peekFlag != 0) && minBufLen != 0) { decryptBuf->buf = BSL_SAL_Calloc(minBufLen, sizeof(uint8_t)); if (decryptBuf->buf == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17257, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } decryptBuf->bufSize = minBufLen; decryptBuf->isHoldBuffer = true; } decryptBuf->end = decryptBuf->bufSize; /* The decrypted record body is in data */ ret = RecConnDecrypt(ctx, state, encryptedMsg, decryptBuf->buf, &decryptBuf->end); if (ret != HITLS_SUCCESS) { goto ERR; } if (!IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { ret = funcs->decryptPostProcess(ctx, state->suiteInfo, encryptedMsg, decryptBuf->buf, &decryptBuf->end); if (ret != HITLS_SUCCESS) { goto ERR; } RecConnSetSeqNum(state, RecConnGetSeqNum(state) + 1); } ret = ProcessDecryptedRecord(ctx, decryptBuf->end, encryptedMsg); if (ret != HITLS_SUCCESS) { goto ERR; } return HITLS_SUCCESS; ERR: if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } return ret; } static int32_t RecordUnexpectedMsg(TLS_Ctx *ctx, RecBuf *decryptBuf, REC_Type recordType) { int32_t ret = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; ctx->recCtx->unexpectedMsgType = recordType; switch (recordType) { case REC_TYPE_HANDSHAKE: ret = RecBufListAddBuffer(ctx->recCtx->hsRecList, decryptBuf); break; case REC_TYPE_APP: ret = RecBufListAddBuffer(ctx->recCtx->appRecList, decryptBuf); break; case REC_TYPE_CHANGE_CIPHER_SPEC: case REC_TYPE_ALERT: default: ret = ctx->method.unexpectedMsgProcessCb(ctx, recordType, decryptBuf->buf, decryptBuf->end, false); if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } return ret; } if (ret != HITLS_SUCCESS) { if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17258, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "process recordType fail", 0, 0, 0, 0); return ret; } ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17259, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecDerefBufList fail", 0, 0, 0, 0); return ret; } return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } #ifdef HITLS_TLS_PROTO_DTLS12 int32_t DtlsCheckVersionField(const TLS_Ctx *ctx, uint16_t version, uint8_t type) { /* Tolerate alerts with non-negotiated version. For example, after the server sends server hello, the client * replies with an earlier version alert */ if (ctx->negotiatedInfo.version == 0u || type == (uint8_t)REC_TYPE_ALERT) { if ((version != HITLS_VERSION_DTLS10) && (version != HITLS_VERSION_DTLS12) && (version != HITLS_VERSION_TLCP_DTLCP11)) { BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15436, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); return HITLS_REC_INVALID_PROTOCOL_VERSION; } } else { if (version != ctx->negotiatedInfo.version) { BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15437, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); return HITLS_REC_INVALID_PROTOCOL_VERSION; } } return HITLS_SUCCESS; } int32_t DtlsCheckRecordHeader(TLS_Ctx *ctx, const RecHdr *hdr) { /** Check the DTLS version, release the resource and return if the version is incorrect */ int32_t ret = DtlsCheckVersionField(ctx, hdr->version, hdr->type); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17261, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DtlsCheckVersionField fail, ret %d", ret, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); } if (RecCastUintToRecType(ctx, hdr->type) == REC_TYPE_UNKNOWN || hdr->bodyLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_RECV_UNEXPECTED_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15438, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid type or body length(0)", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } RecConnState *state = GetReadConnState(ctx); uint32_t maxLenth = (state->suiteInfo != NULL) ? REC_MAX_CIPHER_TEXT_LEN : REC_MAX_PLAIN_LENGTH; if (hdr->bodyLen > maxLenth) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_TOO_BIG_LENGTH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15439, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } uint16_t epoch = REC_EPOCH_GET(hdr->epochSeq); if (epoch == 0 && hdr->type == REC_TYPE_APP && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_RECV_UNEXPECTED_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15440, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a UNEXPECTE record msg: epoch 0's app msg.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_REC_ERR_RECV_UNEXPECTED_MSG; } return HITLS_SUCCESS; } /** * @brief Read message data. * * @param uio [IN] UIO object. * @param inBuf [IN] inBuf Read the buffer. * * @retval HITLS_SUCCESS is successfully read. * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY Uncached data needs to be reread. */ static int32_t ReadDatagram(TLS_Ctx *ctx, RecBuf *inBuf) { if (inBuf->end > inBuf->start) { return HITLS_SUCCESS; } /* Attempt to read the message: The message is read of the whole message */ uint32_t recvLen = 0u; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_READING; #endif #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t ret = BSL_UIO_Read(ctx->rUio, &(inBuf->buf[0]), inBuf->bufSize, &recvLen); #else int32_t ret = BSL_UIO_Read(ctx->uio, &(inBuf->buf[0]), inBuf->bufSize, &recvLen); #endif if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15441, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record read: uio err.%d", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif if (recvLen == 0) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } inBuf->start = 0; // successfully read inBuf->end = recvLen; return HITLS_SUCCESS; } static int32_t DtlsGetRecordHeader(const uint8_t *msg, uint32_t len, RecHdr *hdr) { if (len < REC_DTLS_RECORD_HEADER_LEN) { BSL_ERR_PUSH_ERROR(HITLS_REC_DECODE_ERROR); BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15442, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:dtls packet's length err.", 0, 0, 0, 0); return HITLS_REC_DECODE_ERROR; } /* Parse the record header */ hdr->type = msg[0]; hdr->version = BSL_ByteToUint16(&msg[1]); hdr->bodyLen = BSL_ByteToUint16( &msg[REC_DTLS_RECORD_LENGTH_OFFSET]); // The 11th to 12th bytes of DTLS are the message length. hdr->epochSeq = BSL_ByteToUint64(&msg[REC_DTLS_RECORD_EPOCH_OFFSET]); return HITLS_SUCCESS; } /** * @brief Attempt to read a dtls record message. * * @param ctx [IN] TLS context * @param recordBody [OUT] record body * @param hdr [OUT] record head * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error */ static int32_t TryReadOneDtlsRecord(TLS_Ctx *ctx, uint8_t **recordBody, RecHdr *hdr) { int32_t ret; /** Obtain the record structure information */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; if (IsNeedtoRead(ctx, recordCtx->inBuf)) { ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { return ret; } } /** Read the datagram message: The message may contain multiple records */ ret = ReadDatagram(ctx, recordCtx->inBuf); if (ret != HITLS_SUCCESS) { return ret; } uint8_t *msg = &recordCtx->inBuf->buf[recordCtx->inBuf->start]; uint32_t len = recordCtx->inBuf->end - recordCtx->inBuf->start; ret = DtlsGetRecordHeader(msg, len, hdr); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17262, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DtlsGetRecordHeader fail, ret %d", ret, 0, 0, 0); RecBufClean(recordCtx->inBuf); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, 0, RECORD_HEADER, msg, REC_DTLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif /* Check whether the record length is greater than the buffer size */ if ((REC_DTLS_RECORD_HEADER_LEN + (uint32_t)hdr->bodyLen) > len) { RecBufClean(recordCtx->inBuf); BSL_ERR_PUSH_ERROR(HITLS_REC_DECODE_ERROR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15443, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record:dtls packet's length err.", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } /** Release the read record */ recordCtx->inBuf->start += REC_DTLS_RECORD_HEADER_LEN + hdr->bodyLen; /** Update the read content */ *recordBody = msg + REC_DTLS_RECORD_HEADER_LEN; return HITLS_SUCCESS; } static inline void GenerateCryptMsg(const TLS_Ctx *ctx, const RecHdr *hdr, const uint8_t *recordBody, REC_TextInput *cryptMsg) { cryptMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM cryptMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMac; #endif cryptMsg->type = hdr->type; cryptMsg->version = hdr->version; cryptMsg->text = recordBody; cryptMsg->textLen = hdr->bodyLen; BSL_Uint64ToByte(hdr->epochSeq, cryptMsg->seq); } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) /** * @brief Check whether there are unprocessed handshake messages in the cache. * * @param unprocessedHsMsg [IN] Unprocessed handshake message handle * @param curEpoch [IN] Current epoch * * @retval true: cached * @retval false No cache */ static bool IsExistUnprocessedHsMsg(RecCtx *recCtx) { uint16_t curEpoch = recCtx->readEpoch; UnprocessedHsMsg *unprocessedHsMsg = &recCtx->unprocessedHsMsg; /* Check whether there are cached handshake messages. */ if (unprocessedHsMsg->recordBody == NULL) { return false; } uint16_t epoch = REC_EPOCH_GET(unprocessedHsMsg->hdr.epochSeq); if (curEpoch == epoch) { /* The handshake message of the current epoch needs to be processed */ return true; } if (curEpoch > epoch) { /* Expired messages need to be cleaned up */ (void)memset_s(&unprocessedHsMsg->hdr, sizeof(unprocessedHsMsg->hdr), 0, sizeof(unprocessedHsMsg->hdr)); BSL_SAL_FREE(unprocessedHsMsg->recordBody); } return false; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ static bool IsExistUnprocessedAppMsg(RecCtx *recCtx) { UnprocessedAppMsg *unprocessedAppMsgList = &recCtx->unprocessedAppMsgList; /* Check whether there are cached app messages. */ if (unprocessedAppMsgList->count == 0) { return false; } ListHead *node = NULL; ListHead *tmpNode = NULL; UnprocessedAppMsg *cur = NULL; uint16_t curEpoch = recCtx->readEpoch; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(unprocessedAppMsgList->head)) { cur = LIST_ENTRY(node, UnprocessedAppMsg, head); uint16_t epoch = REC_EPOCH_GET(cur->hdr.epochSeq); if (curEpoch == epoch) { /* The app message of the current epoch needs to be processed */ return true; } } return false; } int32_t RecordBufferUnprocessedMsg(RecCtx *recordCtx, RecHdr *hdr, uint8_t *recordBody) { if (hdr->type == REC_TYPE_HANDSHAKE) { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) CacheNextEpochHsMsg(&recordCtx->unprocessedHsMsg, hdr, recordBody); #endif } else { int32_t ret = UnprocessedAppMsgListAppend(&recordCtx->unprocessedAppMsgList, hdr, recordBody); if (ret != HITLS_SUCCESS) { return ret; } } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17263, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "recv normal disorder message", 0, 0, 0, 0); return HITLS_REC_NORMAL_RECV_DISORDER_MSG; } static int32_t DtlsRecordHeaderProcess(TLS_Ctx *ctx, uint8_t *recordBody, RecHdr *hdr) { int32_t ret = HITLS_SUCCESS; RecCtx *recordCtx = (RecCtx *)ctx->recCtx; ret = DtlsCheckRecordHeader(ctx, hdr); if (ret != HITLS_SUCCESS) { return ret; } uint16_t epoch = REC_EPOCH_GET(hdr->epochSeq); if (epoch != recordCtx->readEpoch) { /* Discard out-of-order messages in SCTP scenarios */ if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP)) { return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } #if defined(HITLS_BSL_UIO_UDP) /* Only the messages of the next epoch are cached */ if ((recordCtx->readEpoch + 1) == epoch) { return RecordBufferUnprocessedMsg(recordCtx, hdr, recordBody); } /* After receiving the message of the previous epoch, the system discards the message. */ return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); #endif } bool isCcsRecv = ctx->method.isRecvCCS(ctx); /* App messages arrive earlier than finished messages and need to be cached */ if (ctx->hsCtx != NULL && isCcsRecv == true && (hdr->type == REC_TYPE_APP || hdr->type == REC_TYPE_ALERT)) { return RecordBufferUnprocessedMsg(recordCtx, hdr, recordBody); } return HITLS_SUCCESS; } static uint8_t *GetUnprocessedMsg(RecCtx *recordCtx, REC_Type recordType, RecHdr *hdr) { uint8_t *recordBody = NULL; #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if ((recordType == REC_TYPE_HANDSHAKE) && IsExistUnprocessedHsMsg(recordCtx)) { (void)memcpy_s(hdr, sizeof(RecHdr), &recordCtx->unprocessedHsMsg.hdr, sizeof(RecHdr)); recordBody = recordCtx->unprocessedHsMsg.recordBody; recordCtx->unprocessedHsMsg.recordBody = NULL; } #endif uint16_t curEpoch = recordCtx->readEpoch; if ((recordType == REC_TYPE_APP) && IsExistUnprocessedAppMsg(recordCtx)) { UnprocessedAppMsg *appMsg = UnprocessedAppMsgGet(&recordCtx->unprocessedAppMsgList, curEpoch); if (appMsg == NULL) { return NULL; } (void)memcpy_s(hdr, sizeof(RecHdr), &appMsg->hdr, sizeof(RecHdr)); recordBody = appMsg->recordBody; appMsg->recordBody = NULL; UnprocessedAppMsgFree(appMsg); } return recordBody; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static int32_t AntiReplay(TLS_Ctx *ctx, RecHdr *hdr) { /* In non-UDP scenarios, anti-replay check is not required */ if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } RecConnState *state = GetReadConnState(ctx); uint16_t epoch = REC_EPOCH_GET(hdr->epochSeq); uint64_t secquence = REC_SEQ_GET(hdr->epochSeq); if (RecAntiReplayCheck(&state->window, secquence) == true) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } if (ctx->isDtlsListen && epoch != 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17264, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "epoch err", 0, 0, 0, 0); return HITLS_REC_ERR_RECV_UNEXPECTED_MSG; } return HITLS_SUCCESS; } #endif static int32_t DtlsTryReadAndCheckRecordMessage(TLS_Ctx *ctx, uint8_t **recordBody, RecHdr *hdr) { int32_t ret = HITLS_SUCCESS; /* Read the new record message */ ret = TryReadOneDtlsRecord(ctx, recordBody, hdr); if (ret != HITLS_SUCCESS) { return ret; } /* Check the record message header. If the message header is not the expected message, cache the message */ return DtlsRecordHeaderProcess(ctx, *recordBody, hdr); } static int32_t DtlsGetRecord(TLS_Ctx *ctx, REC_Type recordType, RecHdr *hdr, uint8_t **recordBody, uint8_t **cachRecord) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; int32_t ret = RecIoBufInit(ctx, recordCtx, true); if (ret != HITLS_SUCCESS) { return ret; } /* Check if there are cached messages that need to be processed */ *recordBody = GetUnprocessedMsg(recordCtx, recordType, hdr); *cachRecord = *recordBody; /* There are no cached messages to process */ if (*recordBody == NULL) { ret = DtlsTryReadAndCheckRecordMessage(ctx, recordBody, hdr); if (ret != HITLS_SUCCESS) { return ret; } } #if defined(HITLS_BSL_UIO_UDP) ret = AntiReplay(ctx, hdr); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(*cachRecord); } #endif return ret; } static int32_t DtlsProcessBufList(TLS_Ctx *ctx, REC_Type recordType, RecBufList *bufList, RecBuf *decryptBuf) { (void)recordType; int32_t ret = RecBufListAddBuffer(bufList, decryptBuf); if (ret != HITLS_SUCCESS) { if (decryptBuf->isHoldBuffer) { BSL_SAL_FREE(decryptBuf->buf); } return ret; } ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } /** * @brief Read a record in the DTLS protocol. * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param len [OUT] Length of the data to be read * @param bufSize [IN] buffer length * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received * @retval HITLS_REC_NORMAL_RECV_DISORDER_MSG Receives out-of-order messages. * */ int32_t DtlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *len, uint32_t bufSize) { RecBufList *bufList = (recordType == REC_TYPE_HANDSHAKE) ? ctx->recCtx->hsRecList : ctx->recCtx->appRecList; if (!RecBufListEmpty(bufList)) { return RecBufListGetBuffer(bufList, data, bufSize, len, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } RecHdr hdr = {0}; /* Pointer for storing buffered messages, which is used during release */ uint8_t *recordBody = NULL; uint8_t *cachRecord = NULL; int32_t ret = DtlsGetRecord(ctx, recordType, &hdr, &recordBody, &cachRecord); if (ret != HITLS_SUCCESS) { return ret; } /* Construct parameters before decryption */ REC_TextInput cryptMsg = {0}; GenerateCryptMsg(ctx, &hdr, recordBody, &cryptMsg); RecBuf decryptBuf = { .buf = data, .bufSize = bufSize }; ret = RecordDecrypt(ctx, &decryptBuf, &cryptMsg); BSL_SAL_FREE(cachRecord); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_BSL_UIO_UDP) /* In UDP scenarios, update the sliding window flag */ if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { RecAntiReplayUpdate(&GetReadConnState(ctx)->window, REC_SEQ_GET(hdr.epochSeq)); } #endif RecClearAlertCount(ctx, cryptMsg.type); #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, false); } #endif /* An unexpected packet is received */ // decryptBuf.isHoldBuffer == false if (recordType != cryptMsg.type) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16513, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "expect type %d, receive type %d", recordType, cryptMsg.type, 0, 0); return RecordUnexpectedMsg(ctx, &decryptBuf, cryptMsg.type); } if (decryptBuf.buf == data) { /* Update the read length */ *len = decryptBuf.end; return HITLS_SUCCESS; } ret = DtlsProcessBufList(ctx, recordType, bufList, &decryptBuf); if (ret != HITLS_SUCCESS) { return ret; } return RecBufListGetBuffer(bufList, data, bufSize, len, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS static int32_t VersionProcess(TLS_Ctx *ctx, uint16_t version, uint8_t type) { if ((ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) && (version != HITLS_VERSION_TLS12)) { /* If the negotiated version is tls1.3, the record version must be tls1.2 */ BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15448, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_DECODE_ERROR); return HITLS_REC_INVALID_PROTOCOL_VERSION; } else if ((ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) && (version != ctx->negotiatedInfo.version)) { BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15449, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); if (((version & 0xff00u) == (ctx->negotiatedInfo.version & 0xff00u)) && type == REC_TYPE_ALERT) { return HITLS_SUCCESS; } ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_REC_INVALID_PROTOCOL_VERSION; } return HITLS_SUCCESS; } int32_t TlsCheckVersionField(TLS_Ctx *ctx, uint16_t version, uint8_t type) { if (ctx->negotiatedInfo.version == 0u) { #ifdef HITLS_TLS_PROTO_TLCP11 if (((version >> 8u) != HITLS_VERSION_TLS_MAJOR) && (version != HITLS_VERSION_TLCP_DTLCP11)) { #else if ((version >> 8u) != HITLS_VERSION_TLS_MAJOR) { #endif BSL_ERR_PUSH_ERROR(HITLS_REC_INVALID_PROTOCOL_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16132, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with illegal version(0x%x).", version, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_PROTOCOL_VERSION); return HITLS_REC_INVALID_PROTOCOL_VERSION; } } else { return VersionProcess(ctx, version, type); } return HITLS_SUCCESS; } int32_t TlsCheckRecordHeader(TLS_Ctx *ctx, const RecHdr *recordHdr) { if (RecCastUintToRecType(ctx, recordHdr->type) == REC_TYPE_UNKNOWN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15450, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid type", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } int32_t ret = TlsCheckVersionField(ctx, recordHdr->version, recordHdr->type); if (ret != HITLS_SUCCESS) { return HITLS_REC_INVALID_PROTOCOL_VERSION; } if (recordHdr->bodyLen + REC_TLS_RECORD_HEADER_LEN > RecGetInitBufferSize(ctx, true)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15451, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } if (recordHdr->bodyLen + REC_TLS_RECORD_HEADER_LEN > ctx->recCtx->inBuf->bufSize) { ret = RecBufResize(ctx->recCtx->inBuf, recordHdr->bodyLen + REC_TLS_RECORD_HEADER_LEN); if (ret != HITLS_SUCCESS) { return ret; } } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13 && recordHdr->bodyLen > REC_MAX_TLS13_ENCRYPTED_LEN) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16125, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a record with invalid length", 0, 0, 0, 0); return RecordSendAlertMsg(ctx, ALERT_LEVEL_FATAL, ALERT_RECORD_OVERFLOW); } #endif return HITLS_SUCCESS; } /** * @brief Read data from the uio of the TLS context into inBuf * * @param ctx [IN] TLS context * @param inBuf [IN] inBuf Read buffer. * @param len [IN] len The length to read, it takes the value of the record header length (5 * bytes) or the entire record length (header + body) * * @retval HITLS_SUCCESS Read successfully * @retval HITLS_REC_ERR_IO_EXCEPTION IO error * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY No cached data needs to be re-read * @retval HITLS_REC_NORMAL_IO_EOF */ int32_t StreamRead(TLS_Ctx *ctx, RecBuf *inBuf, uint32_t len) { uint32_t bytesInRbuf = inBuf->end - inBuf->start; bool readAheadFlag = (ctx->config.tlsConfig.readAhead != 0); if (bytesInRbuf == 0) { inBuf->start = 0; inBuf->end = 0; } // there are enough data in the read buffer if (bytesInRbuf >= len) { return HITLS_SUCCESS; } // right-side available space is less then required len, move data leftwards if (inBuf->bufSize - inBuf->end < len) { for (uint32_t i = 0; i < bytesInRbuf; i++) { inBuf->buf[i] = inBuf->buf[inBuf->start + i]; } inBuf->start = 0; inBuf->end = bytesInRbuf; } uint32_t upperBnd = (!readAheadFlag && inBuf->bufSize >= inBuf->start + len - inBuf->end) ? inBuf->start + len : inBuf->bufSize; do { uint32_t recvLen = 0u; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_READING; #endif #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t ret = BSL_UIO_Read(ctx->rUio, &(inBuf->buf[inBuf->end]), upperBnd - inBuf->end, &recvLen); #else int32_t ret = BSL_UIO_Read(ctx->uio, &(inBuf->buf[inBuf->end]), upperBnd - inBuf->end, &recvLen); #endif if (ret != BSL_SUCCESS) { if (ret == BSL_UIO_IO_EOF) { return HITLS_REC_NORMAL_IO_EOF; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15452, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Fail to call BSL_UIO_Read in StreamRead: [%d]", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif if (recvLen == 0) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } inBuf->end += recvLen; } while (inBuf->end - inBuf->start < len); return HITLS_SUCCESS; } /** * @brief Attempt to read a tls record message. * * @param ctx [IN] TLS context * @param recordBody [OUT] record body * @param hdr [OUT] record head * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error */ int32_t TryReadOneTlsRecord(TLS_Ctx *ctx, uint8_t **recordBody, RecHdr *recHeader) { /* Buffer for reading data */ RecBuf *inBuf = ctx->recCtx->inBuf; if (IsNeedtoRead(ctx, inBuf)) { RecDerefBufList(ctx); } // read record header int32_t ret = StreamRead(ctx, inBuf, REC_TLS_RECORD_HEADER_LEN); if (ret != HITLS_SUCCESS) { return ret; } const uint8_t *recordHeader = &inBuf->buf[inBuf->start]; recHeader->type = recordHeader[0]; recHeader->version = BSL_ByteToUint16(recordHeader + sizeof(uint8_t)); recHeader->bodyLen = BSL_ByteToUint16(recordHeader + REC_TLS_RECORD_LENGTH_OFFSET); ret = TlsCheckRecordHeader(ctx, recHeader); if (ret != HITLS_SUCCESS) { #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, 0, RECORD_HEADER, recordHeader, REC_TLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, recHeader->version, RECORD_HEADER, recordHeader, REC_TLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif uint32_t recHeaderAndBodyLen = REC_TLS_RECORD_HEADER_LEN + (uint32_t)recHeader->bodyLen; // read a whole record: head + body ret = StreamRead(ctx, inBuf, recHeaderAndBodyLen); if (ret != HITLS_SUCCESS) { return ret; } *recordBody = &inBuf->buf[inBuf->start] + REC_TLS_RECORD_HEADER_LEN; inBuf->start += recHeaderAndBodyLen; return HITLS_SUCCESS; } int32_t RecordDecryptPrepare(TLS_Ctx *ctx, uint16_t version, REC_Type recordType, REC_TextInput *cryptMsg) { (void)recordType; (void)version; RecConnState *state = GetReadConnState(ctx); if (state->isWrapped == true) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_SN_WRAPPING); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15454, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record read: sequence number wrap.", 0, 0, 0, 0); return HITLS_REC_ERR_SN_WRAPPING; } if (state->seq == REC_TLS_SN_MAX_VALUE) { state->isWrapped = true; } if (ctx->peekFlag != 0 && recordType != REC_TYPE_APP) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16170, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Peek mode applies only if record type is application.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } RecHdr recordHeader = { 0 }; uint8_t *recordBody = NULL; // read header and body from ctx int32_t ret = TryReadOneTlsRecord(ctx, &recordBody, &recordHeader); if (ret != HITLS_SUCCESS) { return ret; } uint32_t recordBodyLen = (uint32_t)recordHeader.bodyLen; #ifdef HITLS_TLS_PROTO_TLS13 if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13) { if ((recordHeader.type == REC_TYPE_CHANGE_CIPHER_SPEC || recordHeader.type == REC_TYPE_ALERT) && recordBodyLen != 0) { ctx->recCtx->unexpectedMsgType = recordHeader.type; /* In the TLS1.3 scenario, process unencrypted CCS and Alert messages received */ return ctx->method.unexpectedMsgProcessCb(ctx, recordHeader.type, recordBody, recordBodyLen, true); } } #endif cryptMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM cryptMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMac; #endif cryptMsg->type = recordHeader.type; cryptMsg->version = recordHeader.version; cryptMsg->text = recordBody; cryptMsg->textLen = recordBodyLen; BSL_Uint64ToByte(state->seq, cryptMsg->seq); return HITLS_SUCCESS; } /** * @brief Read a record in the TLS protocol. * @attention: Handle record and handle transporting state to receive unexpected record type messages * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param readLen [OUT] Length of the read data * @param num [IN] The read buffer has num bytes * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY Need to re-read * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_ERR_SN_WRAPPING The sequence number is rewound. * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received. * */ int32_t TlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { RecBufList *bufList = (recordType == REC_TYPE_HANDSHAKE) ? ctx->recCtx->hsRecList : ctx->recCtx->appRecList; if (!RecBufListEmpty(bufList)) { return RecBufListGetBuffer(bufList, data, num, readLen, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } int32_t ret = RecIoBufInit(ctx, (RecCtx *)ctx->recCtx, true); if (ret != HITLS_SUCCESS) { return ret; } REC_TextInput encryptedMsg = { 0 }; ret = RecordDecryptPrepare(ctx, ctx->negotiatedInfo.version, recordType, &encryptedMsg); if (ret != HITLS_SUCCESS) { return ret; } RecBuf decryptBuf = {0}; decryptBuf.buf = data; decryptBuf.bufSize = num; ret = RecordDecrypt(ctx, &decryptBuf, &encryptedMsg); if (ret != HITLS_SUCCESS) { return ret; } RecClearAlertCount(ctx, encryptedMsg.type); #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, false); } #endif /* An unexpected message is received */ if (recordType != encryptedMsg.type) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17260, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "expect type %d, receive type %d", recordType, encryptedMsg.type, 0, 0); return RecordUnexpectedMsg(ctx, &decryptBuf, encryptedMsg.type); } if (decryptBuf.buf == data) { /* Update the read length */ *readLen = decryptBuf.end; return HITLS_SUCCESS; } ret = RecBufListAddBuffer(bufList, &decryptBuf); if (ret != HITLS_SUCCESS) { if (decryptBuf.isHoldBuffer) { BSL_SAL_FREE(decryptBuf.buf); } return ret; } return RecBufListGetBuffer(bufList, data, num, readLen, (ctx->peekFlag != 0 && (recordType == REC_TYPE_APP))); } #endif /* HITLS_TLS_PROTO_TLS */ uint32_t APP_GetReadPendingBytes(const TLS_Ctx *ctx) { if (ctx == NULL || ctx->recCtx == NULL || RecBufListEmpty(ctx->recCtx->appRecList)) { return 0; } RecBuf *recBuf = (RecBuf *)BSL_LIST_GET_FIRST(ctx->recCtx->appRecList); if (recBuf == NULL) { return 0; } return recBuf->end - recBuf->start; }
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_read.c
C
unknown
40,459
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_READ_H #define REC_READ_H #include <stdint.h> #include "rec.h" #include "rec_buf.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Read a record in the DTLS protocol * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param len [OUT] Read data length * @param bufSize [IN] buffer length * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received * @retval HITLS_REC_NORMAL_RECV_DISORDER_MSG Receives out-of-order messages * */ int32_t DtlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *len, uint32_t bufSize); #endif /** * @brief Read a record in the TLS protocol * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [OUT] Read data * @param readLen [OUT] Length of the read data * @param num [IN] The read buffer has num bytes * * @retval HITLS_SUCCESS * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG Unexpected message received * */ int32_t TlsRecordRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num); /** * @brief Read data from the UIO of the TLS context to the inBuf * * @param ctx [IN] TLS context * @param inBuf [IN] * @param len [IN] len Length to be read * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_RECV_BUF_EMPTY needs to be read again */ int32_t StreamRead(TLS_Ctx *ctx, RecBuf *inBuf, uint32_t len); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_read.h
C
unknown
2,446
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #include "bsl_sal.h" #include "bsl_module_list.h" #include "tls_binlog_id.h" #include "hitls_error.h" #include "rec.h" #include "bsl_uio.h" #include "record.h" #include "hs.h" #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t REC_RetransmitListAppend(REC_Ctx *recCtx, REC_Type type, const uint8_t *msg, uint32_t len) { RecRetransmitList *retransmitList = &recCtx->retransmitList; RecRetransmitList *retransmitNode = (RecRetransmitList *)BSL_SAL_Calloc(1u, sizeof(RecRetransmitList)); if (retransmitNode == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17277, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } LIST_INIT(&(retransmitNode->head)); retransmitNode->type = type; retransmitNode->msg = BSL_SAL_Dump(msg, len); if (retransmitNode->msg == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17278, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_SAL_FREE(retransmitNode); return HITLS_MEMALLOC_FAIL; } retransmitNode->len = len; if (type == REC_TYPE_CHANGE_CIPHER_SPEC) { retransmitList->isExistCcsMsg = true; } /* insert new node */ LIST_ADD_BEFORE(&retransmitList->head, &retransmitNode->head); return HITLS_SUCCESS; } void REC_RetransmitListClean(REC_Ctx *recCtx) { ListHead *head = NULL; ListHead *tmpHead = NULL; RecRetransmitList *retransmitList = &recCtx->retransmitList; RecRetransmitList *retransmitNode = NULL; retransmitList->isExistCcsMsg = false; LIST_FOR_EACH_ITEM_SAFE(head, tmpHead, &(retransmitList->head)) { LIST_REMOVE(head); retransmitNode = LIST_ENTRY(head, RecRetransmitList, head); BSL_SAL_FREE(retransmitNode->msg); BSL_SAL_FREE(retransmitNode); } return; } static int32_t WriteSingleRetransmitNode(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { int32_t ret = REC_QueryMtu(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = REC_RecOutBufReSet(ctx); if (ret != HITLS_SUCCESS) { return ret; } uint32_t maxRecPayloadLen = 0; ret = REC_GetMaxWriteSize(ctx, &maxRecPayloadLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17360, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetMaxWriteSize fail", 0, 0, 0, 0); return ret; } if (maxRecPayloadLen >= num) { /* Send to the record layer */ ret = REC_Write(ctx, recordType, data, num); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17361, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "send handshake msg to record fail.", 0, 0, 0, 0); return ret; } } else { ret = HS_DtlsSendFragmentHsMsg(ctx, maxRecPayloadLen, data); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } int32_t REC_RetransmitListFlush(TLS_Ctx *ctx) { REC_Ctx *recCtx = ctx->recCtx; RecRetransmitList *retransmitList = &recCtx->retransmitList; RecRetransmitList *retransmitNode = NULL; if (retransmitList->isExistCcsMsg == true) { REC_ActiveOutdatedWriteState(ctx); } int32_t ret = HITLS_SUCCESS; ListHead *head = NULL; ListHead *tmpHead = NULL; LIST_FOR_EACH_ITEM_SAFE(head, tmpHead, &(retransmitList->head)) { retransmitNode = LIST_ENTRY(head, RecRetransmitList, head); /* UDP does not fail to send. Therefore, the sending failure case does not need to be considered. */ ret = WriteSingleRetransmitNode(ctx, retransmitNode->type, retransmitNode->msg, retransmitNode->len); if (ret != HITLS_SUCCESS) { return ret; } if (retransmitNode->type == REC_TYPE_CHANGE_CIPHER_SPEC) { REC_DeActiveOutdatedWriteState(ctx); } } if (ctx->config.tlsConfig.isFlightTransmitEnable) { (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_FLUSH, 0, NULL); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_retransmit.c
C
unknown
4,707
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_TLS_PROTO_DTLS12 #include "securec.h" #include "bsl_module_list.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "hitls_error.h" #include "rec.h" #include "rec_unprocessed_msg.h" #ifdef HITLS_BSL_UIO_UDP void CacheNextEpochHsMsg(UnprocessedHsMsg *unprocessedHsMsg, const RecHdr *hdr, const uint8_t *recordBody) { /* only out-of-order finished messages need to be cached */ if (hdr->type != REC_TYPE_HANDSHAKE) { return; } /* only cache one */ if (unprocessedHsMsg->recordBody != NULL) { return; } unprocessedHsMsg->recordBody = (uint8_t *)BSL_SAL_Dump(recordBody, hdr->bodyLen); if (unprocessedHsMsg->recordBody == NULL) { return; } (void)memcpy_s(&unprocessedHsMsg->hdr, sizeof(RecHdr), hdr, sizeof(RecHdr)); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15446, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "cache next epoch hs msg", 0, 0, 0, 0); return; } #endif /* HITLS_BSL_UIO_UDP */ UnprocessedAppMsg *UnprocessedAppMsgNew(void) { UnprocessedAppMsg *msg = (UnprocessedAppMsg *)BSL_SAL_Calloc(1, sizeof(UnprocessedAppMsg)); if (msg == NULL) { return NULL; } LIST_INIT(&msg->head); return msg; } void UnprocessedAppMsgFree(UnprocessedAppMsg *msg) { if (msg != NULL) { BSL_SAL_FREE(msg->recordBody); BSL_SAL_FREE(msg); } return; } void UnprocessedAppMsgListInit(UnprocessedAppMsg *appMsgList) { if (appMsgList == NULL) { return; } appMsgList->count = 0; appMsgList->recordBody = NULL; LIST_INIT(&appMsgList->head); return; } void UnprocessedAppMsgListDeinit(UnprocessedAppMsg *appMsgList) { ListHead *node = NULL; ListHead *tmpNode = NULL; UnprocessedAppMsg *cur = NULL; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(appMsgList->head)) { cur = LIST_ENTRY(node, UnprocessedAppMsg, head); LIST_REMOVE(node); /* releasing nodes and deleting user data */ UnprocessedAppMsgFree(cur); } appMsgList->count = 0; return; } int32_t UnprocessedAppMsgListAppend(UnprocessedAppMsg *appMsgList, const RecHdr *hdr, const uint8_t *recordBody) { /* prevent oversize */ if (appMsgList->count >= UNPROCESSED_APP_MSG_COUNT_MAX) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } UnprocessedAppMsg *appNode = UnprocessedAppMsgNew(); if (appNode == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15805, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Buffer app record: Malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } appNode->recordBody = (uint8_t*)BSL_SAL_Dump(recordBody, hdr->bodyLen); if (appNode->recordBody == NULL) { UnprocessedAppMsgFree(appNode); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15806, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Buffer app record: Malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(&appNode->hdr, sizeof(RecHdr), hdr, sizeof(RecHdr)); LIST_ADD_BEFORE(&appMsgList->head, &appNode->head); appMsgList->count++; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15807, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "Buffer app record: count is %u.", appMsgList->count, 0, 0, 0); return HITLS_SUCCESS; } UnprocessedAppMsg *UnprocessedAppMsgGet(UnprocessedAppMsg *appMsgList, uint16_t curEpoch) { ListHead *next = appMsgList->head.next; if (next == &appMsgList->head) { return NULL; } ListHead *node = NULL; ListHead *tmpNode = NULL; UnprocessedAppMsg *cur = NULL; LIST_FOR_EACH_ITEM_SAFE(node, tmpNode, &(appMsgList->head)) { cur = LIST_ENTRY(node, UnprocessedAppMsg, head); uint16_t epoch = REC_EPOCH_GET(cur->hdr.epochSeq); if (curEpoch == epoch) { /* remove a node and release it by the outside */ LIST_REMOVE(node); appMsgList->count--; return cur; } } return NULL; } #endif /* HITLS_TLS_PROTO_DTLS12 */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_unprocessed_msg.c
C
unknown
4,766
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_UNPROCESSED_MSG_H #define REC_UNPROCESSED_MSG_H #include <stdint.h> #include "bsl_module_list.h" #include "rec_header.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_TLS_PROTO_DTLS12 typedef struct { RecHdr hdr; /* record header */ uint8_t *recordBody; /* record body */ } UnprocessedHsMsg; /* Unprocessed handshake messages */ /* rfc6083 4.7 Handshake User messages that arrive between ChangeCipherSpec and Finished messages and use the new epoch have probably passed the Finished message and MUST be buffered by DTLS until the Finished message is read. */ typedef struct { ListHead head; uint32_t count; /* Number of cached record messages */ RecHdr hdr; /* record header */ uint8_t *recordBody; /* record body */ } UnprocessedAppMsg; /* Unprocessed App messages: App messages that are out of order with finished */ void CacheNextEpochHsMsg(UnprocessedHsMsg *unprocessedHsMsg, const RecHdr *hdr, const uint8_t *recordBody); UnprocessedAppMsg *UnprocessedAppMsgNew(void); void UnprocessedAppMsgFree(UnprocessedAppMsg *msg); void UnprocessedAppMsgListInit(UnprocessedAppMsg *appMsgList); void UnprocessedAppMsgListDeinit(UnprocessedAppMsg *appMsgList); int32_t UnprocessedAppMsgListAppend(UnprocessedAppMsg *appMsgList, const RecHdr *hdr, const uint8_t *recordBody); UnprocessedAppMsg *UnprocessedAppMsgGet(UnprocessedAppMsg *appMsgList, uint16_t curEpoch); #endif // HITLS_TLS_PROTO_DTLS12 #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_unprocessed_msg.h
C
unknown
2,153
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #include "securec.h" #include "bsl_sal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_config.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "tls.h" #include "uio_base.h" #include "record.h" #include "hs_ctx.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif #include "hs.h" #include "rec_crypto.h" RecConnState *GetWriteConnState(const TLS_Ctx *ctx) { /** Obtain the record structure. */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; return recordCtx->writeStates.currentState; } static void OutbufUpdate(uint32_t *start, uint32_t startvalue, uint32_t *end, uint32_t endvalue) { /** Commit the record to be written */ *start = startvalue; *end = endvalue; return; } static int32_t CheckEncryptionLimits(TLS_Ctx *ctx, RecConnState *state) { (void)ctx; if (state->suiteInfo != NULL && #ifdef HITLS_TLS_FEATURE_KEY_UPDATE ctx->isKeyUpdateRequest == false && #endif (state->suiteInfo->cipherAlg == HITLS_CIPHER_AES_128_GCM || state->suiteInfo->cipherAlg == HITLS_CIPHER_AES_256_GCM) && RecConnGetSeqNum(state) > REC_MAX_AES_GCM_ENCRYPTION_LIMIT) { BSL_ERR_PUSH_ERROR(HITLS_REC_ENCRYPTED_NUMBER_OVERFLOW); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16188, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "AES-GCM record encrypted times overflow", 0, 0, 0, 0); return HITLS_REC_ENCRYPTED_NUMBER_OVERFLOW; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_DTLS12 // Write the data message. static int32_t DatagramWrite(TLS_Ctx *ctx, RecBuf *buf) { uint32_t total = buf->end - buf->start; /* Attempt to write */ uint32_t sendLen = 0u; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_WRITING; #endif int32_t ret = BSL_UIO_Write(ctx->uio, &(buf->buf[buf->start]), total, &sendLen); /* Two types of failures occur in the packet transfer scenario: * a. The bottom layer directly returns a failure message. * b. Only some data packets are sent. * (sendLen != total) && (sendLen != 0) checks whether the returned result is null, but only part of the data is sent */ if ((ret != BSL_SUCCESS) || ((sendLen != 0) && (sendLen != total))) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15664, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record send: IO exception. %d\n", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } if (sendLen == 0) { return HITLS_REC_NORMAL_IO_BUSY; } buf->start = 0; buf->end = 0; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif return HITLS_SUCCESS; } void DtlsPlainMsgGenerate(REC_TextInput *plainMsg, const TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen, uint64_t epochSeq) { plainMsg->type = recordType; plainMsg->text = data; plainMsg->textLen = plainLen; plainMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM plainMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMac; #endif if (ctx->negotiatedInfo.version == 0) { plainMsg->version = HITLS_VERSION_DTLS10; if (IS_SUPPORT_TLCP(ctx->config.tlsConfig.originVersionMask)) { plainMsg->version = HITLS_VERSION_TLCP_DTLCP11; } } else { plainMsg->version = ctx->negotiatedInfo.version; } BSL_Uint64ToByte(epochSeq, plainMsg->seq); } static inline void DtlsRecordHeaderPack(uint8_t *outBuf, REC_Type recordType, uint16_t version, uint64_t epochSeq, uint32_t cipherTextLen) { outBuf[0] = recordType; BSL_Uint16ToByte(version, &outBuf[1]); BSL_Uint64ToByte(epochSeq, &outBuf[REC_DTLS_RECORD_EPOCH_OFFSET]); BSL_Uint16ToByte((uint16_t)cipherTextLen, &outBuf[REC_DTLS_RECORD_LENGTH_OFFSET]); } static int32_t DtlsTrySendMessage(TLS_Ctx *ctx, RecCtx *recordCtx, REC_Type recordType, RecConnState *state) { /* Notify the uio whether the service message is being sent. rfc6083 4.4. Stream Usage: For non-app messages, the * sctp stream id number must be 0 */ bool isAppMsg = (recordType == REC_TYPE_APP); (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_SCTP_MASK_APP_MESSAGE, sizeof(isAppMsg), &isAppMsg); int32_t ret = DatagramWrite(ctx, recordCtx->outBuf); if (ret != HITLS_SUCCESS) { /* Does not cache messages in the DTLS */ recordCtx->outBuf->start = 0; recordCtx->outBuf->end = 0; return ret; } #if defined(HITLS_BSL_UIO_UDP) ret = RecDerefBufList(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, true); } #endif /** Add the record sequence */ RecConnSetSeqNum(state, state->seq + 1); return HITLS_SUCCESS; } // Write a record for the DTLS protocol int32_t DtlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { /** Obtain the record structure */ RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnState *state = GetWriteConnState(ctx); if (state->seq > REC_DTLS_SN_MAX_VALUE) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_SN_WRAPPING); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15665, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: sequence number wrap.", 0, 0, 0, 0); return HITLS_REC_ERR_SN_WRAPPING; } uint32_t cipherTextLen = RecGetCryptoFuncs(state->suiteInfo)->calCiphertextLen(ctx, state->suiteInfo, num, false); if (cipherTextLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15666, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: cipherTextLen(0) error.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } int32_t ret = RecIoBufInit(ctx, recordCtx, false); if (ret != HITLS_SUCCESS) { return ret; } const uint32_t outBufLen = REC_DTLS_RECORD_HEADER_LEN + cipherTextLen; if (outBufLen > recordCtx->outBuf->bufSize) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_BUFFER_NOT_ENOUGH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15667, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DTLS record write error: msg len = %u, buf len = %u.", outBufLen, recordCtx->outBuf->bufSize, 0, 0); return HITLS_REC_ERR_BUFFER_NOT_ENOUGH; } /* Before encryption, construct plaintext parameters */ REC_TextInput plainMsg = {0}; uint64_t epochSeq = REC_EPOCHSEQ_CAL(RecConnGetEpoch(state), state->seq); DtlsPlainMsgGenerate(&plainMsg, ctx, recordType, data, num, epochSeq); /** Obtain the cache address */ uint8_t *outBuf = &recordCtx->outBuf->buf[0]; DtlsRecordHeaderPack(outBuf, recordType, plainMsg.version, epochSeq, cipherTextLen); ret = CheckEncryptionLimits(ctx, state); if (ret != HITLS_SUCCESS) { return ret; } /** Encrypt the record body */ ret = RecConnEncrypt(ctx, state, &plainMsg, &outBuf[REC_DTLS_RECORD_HEADER_LEN], cipherTextLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17280, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecConnEncrypt fail", 0, 0, 0, 0); return ret; } OutbufUpdate(&recordCtx->outBuf->start, 0, &recordCtx->outBuf->end, outBufLen); #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(1, 0, RECORD_HEADER, outBuf, REC_DTLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif return DtlsTrySendMessage(ctx, recordCtx, recordType, state); } #endif /* HITLS_TLS_PROTO_DTLS12 */ #ifdef HITLS_TLS_PROTO_TLS // Writes data to the UIO of the TLS context. int32_t StreamWrite(TLS_Ctx *ctx, RecBuf *buf) { uint32_t total = buf->end - buf->start; int32_t ret = BSL_SUCCESS; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_WRITING; #endif do { uint32_t sendLen = 0u; ret = BSL_UIO_Write(ctx->uio, &(buf->buf[buf->start]), total, &sendLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15668, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record send: IO exception. %d\n", ret, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } if (sendLen == 0) { return HITLS_REC_NORMAL_IO_BUSY; } buf->start += sendLen; total -= sendLen; } while (buf->start < buf->end); buf->start = 0; buf->end = 0; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif return HITLS_SUCCESS; } static void TlsPlainMsgGenerate(REC_TextInput *plainMsg, const TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen) { plainMsg->type = recordType; plainMsg->text = data; plainMsg->textLen = plainLen; plainMsg->negotiatedVersion = ctx->negotiatedInfo.version; #ifdef HITLS_TLS_FEATURE_ETM plainMsg->isEncryptThenMac = ctx->negotiatedInfo.isEncryptThenMacWrite; #endif if (ctx->negotiatedInfo.version != 0) { plainMsg->version = #ifdef HITLS_TLS_PROTO_TLS13 (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) ? HITLS_VERSION_TLS12 : #endif ctx->negotiatedInfo.version; } else { plainMsg->version = #ifdef HITLS_TLS_PROTO_TLS13 (ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13) ? HITLS_VERSION_TLS12 : #endif ctx->config.tlsConfig.maxVersion; } if (ctx->hsCtx != NULL && ctx->hsCtx->state == TRY_SEND_CLIENT_HELLO && ctx->state != CM_STATE_RENEGOTIATION && #ifdef HITLS_TLS_PROTO_TLS13 ctx->hsCtx->haveHrr == false && #endif #ifdef HITLS_TLS_PROTO_TLCP11 ctx->config.tlsConfig.maxVersion != HITLS_VERSION_TLCP_DTLCP11 && #endif ctx->config.tlsConfig.maxVersion > HITLS_VERSION_TLS10) { plainMsg->version = HITLS_VERSION_TLS10; } BSL_Uint64ToByte(GetWriteConnState(ctx)->seq, plainMsg->seq); } static inline void TlsRecordHeaderPack(uint8_t *outBuf, REC_Type recordType, uint16_t version, uint32_t cipherTextLen) { outBuf[0] = recordType; BSL_Uint16ToByte(version, &outBuf[1]); BSL_Uint16ToByte((uint16_t)cipherTextLen, &outBuf[REC_TLS_RECORD_LENGTH_OFFSET]); } static int32_t SendRecord(TLS_Ctx *ctx, RecCtx *recordCtx, RecConnState *state, uint64_t seq, REC_Type recordType) { (void)recordType; int32_t ret = StreamWrite(ctx, recordCtx->outBuf); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) != 0 && (recordType == REC_TYPE_APP)) { RecTryFreeRecBuf(ctx, true); } #endif /** Add the record sequence */ RecConnSetSeqNum(state, seq + 1); return HITLS_SUCCESS; } int32_t REC_OutBufFlush(TLS_Ctx *ctx) { RecBuf *writeBuf = ctx->recCtx->outBuf; if (writeBuf == NULL || writeBuf->start == writeBuf->end) { return HITLS_SUCCESS; // No data to flush } if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return HITLS_SUCCESS; } RecConnState *state = GetWriteConnState(ctx); /* The Recordtype is REC_TYPE_HANDSHAKE to not relase outbuffer in HITLS_MODE_RELEASE_BUFFERS mode */ int32_t ret = SendRecord(ctx, ctx->recCtx, state, state->seq, REC_TYPE_HANDSHAKE); if (ret != HITLS_SUCCESS) { return ret; } ctx->recCtx->pendingData = NULL; ctx->recCtx->pendingDataSize = 0; return HITLS_SUCCESS; } static int32_t SequenceCompare(RecConnState *state, uint64_t value) { if (state->isWrapped == true) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_SN_WRAPPING); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15670, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: sequence number wrap.", 0, 0, 0, 0); return HITLS_REC_ERR_SN_WRAPPING; } if (state->seq == value) { state->isWrapped = true; } return HITLS_SUCCESS; } static int32_t LengthCheck(uint32_t ciphertextLen, const uint32_t outBufLen, RecBuf *writeBuf) { if (ciphertextLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15671, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: cipherTextLen(0) error.", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } if (outBufLen > writeBuf->bufSize) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_BUFFER_NOT_ENOUGH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15672, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: buffer is not enough.", 0, 0, 0, 0); return HITLS_REC_ERR_BUFFER_NOT_ENOUGH; } return HITLS_SUCCESS; } static const uint8_t *GetPlainMsgData(RecordPlaintext *recPlaintext, const uint8_t *data) { (void)recPlaintext; return #ifdef HITLS_TLS_PROTO_TLS13 recPlaintext->isTlsInnerPlaintext ? recPlaintext->plainData : #endif data; } // Write a record in the TLS protocol, serialize a record message, and send the message int32_t TlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { RecConnState *state = GetWriteConnState(ctx); RecordPlaintext recPlaintext = {0}; REC_TextInput plainMsg = {0}; int32_t ret = SequenceCompare(state, REC_TLS_SN_MAX_VALUE); if (ret != HITLS_SUCCESS) { return ret; } ret = RecIoBufInit(ctx, (RecCtx *)ctx->recCtx, false); if (ret != HITLS_SUCCESS) { return ret; } RecBuf *writeBuf = ctx->recCtx->outBuf; /* Check whether the cache exists */ if (writeBuf->end > writeBuf->start) { return SendRecord(ctx, ctx->recCtx, state, state->seq, recordType); } const RecCryptoFunc *funcs = RecGetCryptoFuncs(state->suiteInfo); ret = funcs->encryptPreProcess(ctx, recordType, data, num, &recPlaintext); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17281, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encryptPreProcess fail", 0, 0, 0, 0); return ret; } uint32_t ciphertextLen = funcs->calCiphertextLen(ctx, state->suiteInfo, recPlaintext.plainLen, false); const uint32_t outBufLen = REC_TLS_RECORD_HEADER_LEN + ciphertextLen; ret = LengthCheck(ciphertextLen, outBufLen, writeBuf); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(recPlaintext.plainData); return ret; } /* If the value is not tls13, use the input parameter data */ const uint8_t *plainMsgData = GetPlainMsgData(&recPlaintext, data); (void)TlsPlainMsgGenerate(&plainMsg, ctx, recPlaintext.recordType, plainMsgData, recPlaintext.plainLen); (void)TlsRecordHeaderPack(writeBuf->buf, recPlaintext.recordType, plainMsg.version, ciphertextLen); ret = CheckEncryptionLimits(ctx, state); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(recPlaintext.plainData); return ret; } /** Encrypt the record body */ ret = RecConnEncrypt(ctx, state, &plainMsg, writeBuf->buf + REC_TLS_RECORD_HEADER_LEN, ciphertextLen); BSL_SAL_FREE(recPlaintext.plainData); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(1, recordType, RECORD_HEADER, writeBuf->buf, REC_TLS_RECORD_HEADER_LEN, ctx, ctx->config.tlsConfig.msgArg); #endif OutbufUpdate(&writeBuf->start, 0, &writeBuf->end, outBufLen); return SendRecord(ctx, ctx->recCtx, state, state->seq, recordType); } #endif /* HITLS_TLS_PROTO_TLS */ #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t REC_FlightTransmit(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) ret = REC_QueryMtu(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_FLUSH, 0, NULL); if (ret == BSL_UIO_IO_BUSY) { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_REC_NORMAL_IO_BUSY; } bool exceeded = false; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_MTU_EXCEEDED, sizeof(bool), &exceeded); if (exceeded) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17362, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: get EMSGSIZE error.", 0, 0, 0, 0); ctx->needQueryMtu = true; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ return HITLS_REC_NORMAL_IO_BUSY; } if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_IO_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16110, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "fail to send handshake message in bUio.", 0, 0, 0, 0); return HITLS_REC_ERR_IO_EXCEPTION; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_FLIGHT */
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_write.c
C
unknown
17,749
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef REC_WRITE_H #define REC_WRITE_H #include <stdint.h> #include "rec.h" #include "rec_buf.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Write a record in TLS * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [IN] Data to be written * @param plainLen [IN] plain length * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t TlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen); #ifdef HITLS_TLS_PROTO_DTLS12 /** * @brief Write a record in DTLS * * @param ctx [IN] TLS context * @param recordType [IN] Record type * @param data [IN] Data to be written * @param plainLen [IN] plain length * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy * @retval HITLS_REC_ERR_SN_WRAPPING Sequence number wrap */ int32_t DtlsRecordWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen); #endif /** * @brief Write data to the UIO of the TLS context * * @param ctx [IN] TLS context * @param buf [IN] Send buffer * * @retval HITLS_SUCCESS * @retval HITLS_REC_ERR_IO_EXCEPTION I/O error * @retval HITLS_REC_NORMAL_IO_BUSY I/O busy */ int32_t StreamWrite(TLS_Ctx *ctx, RecBuf *buf); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
tls/record/src/rec_write.h
C
unknown
2,025
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "securec.h" #include "bsl_sal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "hitls_error.h" #include "hitls_config.h" #include "rec.h" #include "bsl_uio.h" #include "rec_write.h" #include "rec_read.h" #include "rec_crypto.h" #include "hs.h" #include "alert.h" #include "record.h" // Release RecStatesSuite static void RecConnStatesDeinit(RecCtx *recordCtx) { RecConnStateFree(recordCtx->readStates.currentState); RecConnStateFree(recordCtx->writeStates.currentState); return; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static void RecCmpPmtu(const TLS_Ctx *ctx, uint32_t *recSize) { if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { uint32_t pmtuLimit = ctx->config.pmtu; /* If miniaturization is enabled in the dtls over udp scenario, the mtu size is used */ *recSize = (*recSize > pmtuLimit) ? pmtuLimit : *recSize; } } #endif #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS void RecTryFreeRecBuf(TLS_Ctx *ctx, bool isOut) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; if (isOut) { if (recordCtx->outBuf != NULL && recordCtx->outBuf->start == recordCtx->outBuf->end) { RecBufFree(recordCtx->outBuf); recordCtx->outBuf = NULL; } } else { if (recordCtx->inBuf != NULL && recordCtx->inBuf->start == recordCtx->inBuf->end) { RecBufFree(recordCtx->inBuf); recordCtx->inBuf = NULL; } } return; } #endif uint32_t REC_GetOutBufPendingSize(const TLS_Ctx *ctx) { RecBuf *writeBuf = ctx->recCtx->outBuf; if (writeBuf == NULL) { return 0; } return writeBuf->start > writeBuf->end ? 0 : writeBuf->end - writeBuf->start; } int32_t RecIoBufInit(TLS_Ctx *ctx, RecCtx *recordCtx, bool isRead) { RecBuf **ioBuf = isRead ? &recordCtx->inBuf : &recordCtx->outBuf; if (*ioBuf == NULL) { uint32_t initSize = RecGetInitBufferSize(ctx, isRead); if (isRead && ctx->config.tlsConfig.recInbufferSize != 0) { initSize = ctx->config.tlsConfig.recInbufferSize; } *ioBuf = RecBufNew(initSize); if (*ioBuf == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15532, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: malloc fail.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } } return HITLS_SUCCESS; } static uint32_t RecGetDefaultBufferSize(bool isDtls, bool isRead) { (void)isDtls; uint32_t recHeaderLen = #ifdef HITLS_TLS_PROTO_DTLS12 isDtls ? REC_DTLS_RECORD_HEADER_LEN : #endif REC_TLS_RECORD_HEADER_LEN; uint32_t overHead = REC_MAX_WRITE_ENCRYPTED_OVERHEAD; if (isRead) { overHead = REC_MAX_READ_ENCRYPTED_OVERHEAD; } return recHeaderLen + REC_MAX_PLAIN_TEXT_LENGTH + overHead; } static uint32_t RecGetReadBufferSize(const TLS_Ctx *ctx) { uint32_t recSize = RecGetDefaultBufferSize(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), true); if (ctx->negotiatedInfo.recordSizeLimit != 0 && ctx->negotiatedInfo.recordSizeLimit <= REC_MAX_PLAIN_TEXT_LENGTH) { recSize -= REC_MAX_PLAIN_TEXT_LENGTH - ctx->negotiatedInfo.recordSizeLimit; if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13) { recSize--; } } return recSize; } static uint32_t RecGetWriteBufferSize(const TLS_Ctx *ctx) { uint32_t recSize = RecGetDefaultBufferSize(IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask), false); uint32_t maxSendFragment = #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT (uint32_t)ctx->config.tlsConfig.maxSendFragment == 0 ? REC_MAX_PLAIN_TEXT_LENGTH : (uint32_t)ctx->config.tlsConfig.maxSendFragment; #else REC_MAX_PLAIN_TEXT_LENGTH; #endif recSize -= REC_MAX_PLAIN_TEXT_LENGTH - maxSendFragment; if (ctx->negotiatedInfo.peerRecordSizeLimit != 0 && ctx->negotiatedInfo.peerRecordSizeLimit <= maxSendFragment) { recSize -= maxSendFragment - ctx->negotiatedInfo.peerRecordSizeLimit; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { recSize--; } } #if defined(HITLS_BSL_UIO_UDP) RecCmpPmtu(ctx, &recSize); #endif return recSize; } uint32_t RecGetInitBufferSize(const TLS_Ctx *ctx, bool isRead) { /* If the TLS protocol is used, there is no PMTU limit */ return isRead ? RecGetReadBufferSize(ctx) : RecGetWriteBufferSize(ctx); } int32_t RecDerefBufList(TLS_Ctx *ctx) { int32_t ret = RecBufListDereference(ctx->recCtx->appRecList); if (ret != HITLS_SUCCESS) { return ret; } return RecBufListDereference(ctx->recCtx->hsRecList); } static int32_t InnerRecRead(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { (void)recordType; (void)readLen; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return DtlsRecordRead(ctx, recordType, data, readLen, num); } #endif #ifdef HITLS_TLS_PROTO_TLS return TlsRecordRead(ctx, recordType, data, readLen, num); #else BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17294, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t InnerRecWrite(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif uint32_t maxWriteSize; int32_t ret = REC_GetMaxWriteSize(ctx, &maxWriteSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17295, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetMaxWriteSize fail", 0, 0, 0, 0); return ret; } if (num > maxWriteSize) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15539, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record wrtie: plain length is too long.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_ERR_TOO_BIG_LENGTH); return HITLS_REC_ERR_TOO_BIG_LENGTH; } #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { /* DTLS */ return DtlsRecordWrite(ctx, recordType, data, num); } #endif #ifdef HITLS_TLS_PROTO_TLS return TlsRecordWrite(ctx, recordType, data, num); #else BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17296, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t RecConnStatesInit(RecCtx *recordCtx) { recordCtx->recRead = InnerRecRead; recordCtx->recWrite = InnerRecWrite; recordCtx->readStates.currentState = RecConnStateNew(); if (recordCtx->readStates.currentState == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17297, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StateNew fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } recordCtx->writeStates.currentState = RecConnStateNew(); if (recordCtx->writeStates.currentState == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17298, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StateNew fail", 0, 0, 0, 0); RecConnStateFree(recordCtx->readStates.currentState); recordCtx->readStates.currentState = NULL; BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } static int32_t RecBufInit(TLS_Ctx *ctx, RecCtx *newRecCtx) { #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_RELEASE_BUFFERS) == 0) { #endif int32_t ret = RecIoBufInit(ctx, newRecCtx, true); if (ret != HITLS_SUCCESS) { return ret; } ret = RecIoBufInit(ctx, newRecCtx, false); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_MODE_RELEASE_BUFFERS } #endif newRecCtx->hsRecList = RecBufListNew(); newRecCtx->appRecList = RecBufListNew(); if (newRecCtx->hsRecList == NULL || newRecCtx->appRecList == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17299, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "BufListNew fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } static void RecDeInit(RecCtx *recordCtx) { RecBufFree(recordCtx->outBuf); RecBufFree(recordCtx->inBuf); RecBufListFree(recordCtx->hsRecList); RecBufListFree(recordCtx->appRecList); RecConnStatesDeinit(recordCtx); RecConnStateFree(recordCtx->readStates.pendingState); RecConnStateFree(recordCtx->writeStates.pendingState); RecConnStateFree(recordCtx->readStates.outdatedState); RecConnStateFree(recordCtx->writeStates.outdatedState); #ifdef HITLS_TLS_PROTO_DTLS12 UnprocessedAppMsgListDeinit(&recordCtx->unprocessedAppMsgList); #if defined(HITLS_BSL_UIO_UDP) BSL_SAL_FREE(recordCtx->unprocessedHsMsg.recordBody); REC_RetransmitListClean(recordCtx); #endif #endif /* HITLS_TLS_PROTO_DTLS12 */ } int32_t REC_Init(TLS_Ctx *ctx) { if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17300, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ctx null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } if (ctx->recCtx != NULL) { return HITLS_SUCCESS; } RecCtx *newRecCtx = (RecCtx *)BSL_SAL_Calloc(1, sizeof(RecCtx)); if (newRecCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15531, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: malloc fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } #ifdef HITLS_TLS_PROTO_DTLS12 UnprocessedAppMsgListInit(&newRecCtx->unprocessedAppMsgList); #ifdef HITLS_BSL_UIO_UDP LIST_INIT(&newRecCtx->retransmitList.head); #endif #endif int32_t ret = RecBufInit(ctx, newRecCtx); if (ret != HITLS_SUCCESS) { goto ERR; } ret = RecConnStatesInit(newRecCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15534, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: init connect state fail.", 0, 0, 0, 0); goto ERR; } ctx->recCtx = newRecCtx; return HITLS_SUCCESS; ERR: RecDeInit(newRecCtx); BSL_SAL_FREE(newRecCtx); return ret; } void REC_DeInit(TLS_Ctx *ctx) { if (ctx != NULL && ctx->recCtx != NULL) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecDeInit(recordCtx); BSL_SAL_FREE(ctx->recCtx); } return; } bool REC_ReadHasPending(const TLS_Ctx *ctx) { if ((ctx == NULL) || (ctx->recCtx == NULL)) { return false; } RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecBuf *inBuf = recordCtx->inBuf; if (inBuf == NULL) { return false; } if (inBuf->end != inBuf->start) { return true; } return false; } int32_t REC_Read(TLS_Ctx *ctx, REC_Type recordType, uint8_t *data, uint32_t *readLen, uint32_t num) { if ((ctx == NULL) || (ctx->recCtx == NULL) || (data == NULL) || (ctx->alertCtx == NULL)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15535, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: input invalid parameter.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } return ctx->recCtx->recRead(ctx, recordType, data, readLen, num); } int32_t REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { if ((ctx == NULL) || (ctx->recCtx == NULL) || (num != 0 && data == NULL) || (num == 0 && recordType != REC_TYPE_APP)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15537, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: input null pointer.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } int32_t ret = ctx->recCtx->recWrite(ctx, recordType, data, num); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if (ret != HITLS_SUCCESS) { if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return ret; } bool exceeded = false; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_MTU_EXCEEDED, sizeof(bool), &exceeded); if (exceeded) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17362, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record write: get EMSGSIZE error.", 0, 0, 0, 0); ctx->needQueryMtu = true; } } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ return ret; } #if defined(HITLS_BSL_UIO_UDP) void REC_ActiveOutdatedWriteState(TLS_Ctx *ctx) { RecCtx *recCtx = (RecCtx *)ctx->recCtx; RecConnStates *writeStates = &recCtx->writeStates; writeStates->pendingState = writeStates->currentState; writeStates->currentState = writeStates->outdatedState; writeStates->outdatedState = NULL; return; } void REC_DeActiveOutdatedWriteState(TLS_Ctx *ctx) { RecCtx *recCtx = (RecCtx *)ctx->recCtx; RecConnStates *writeStates = &recCtx->writeStates; writeStates->outdatedState = writeStates->currentState; writeStates->currentState = writeStates->pendingState; writeStates->pendingState = NULL; return; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ static void FreeDataAndState(RecConnSuitInfo *clientSuitInfo, RecConnSuitInfo *serverSuitInfo, RecConnState *readState, RecConnState *writeState) { BSL_SAL_CleanseData((void *)clientSuitInfo, sizeof(RecConnSuitInfo)); BSL_SAL_CleanseData((void *)serverSuitInfo, sizeof(RecConnSuitInfo)); RecConnStateFree(readState); RecConnStateFree(writeState); } int32_t REC_InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param) { if (ctx == NULL || ctx->recCtx == NULL || param == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return RETURN_ERROR_NUMBER_PROCESS(HITLS_INTERNAL_EXCEPTION, BINLOG_ID15540, "Record: ctx null"); } int32_t ret = HITLS_MEMALLOC_FAIL; RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnSuitInfo clientSuitInfo = {0}; RecConnSuitInfo serverSuitInfo = {0}; RecConnSuitInfo *out = NULL; RecConnSuitInfo *in = NULL; RecConnState *readState = RecConnStateNew(); RecConnState *writeState = RecConnStateNew(); if (readState == NULL || writeState == NULL) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17301, "StateNew fail"); goto ERR; } /* 1.Generate a secret */ ret = RecConnKeyBlockGen(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), param, &clientSuitInfo, &serverSuitInfo); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17302, "KeyBlockGen fail"); goto ERR; } /* 2.Set the corresponding read/write pending state */ out = (param->isClient == true) ? &clientSuitInfo : &serverSuitInfo; in = (param->isClient == true) ? &serverSuitInfo : &clientSuitInfo; ret = RecConnStateSetCipherInfo(writeState, out); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17303, "SetCipherInfo fail"); goto ERR; } ret = RecConnStateSetCipherInfo(readState, in); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17304, "SetCipherInfo fail"); goto ERR; } /* Clear sensitive information */ FreeDataAndState(&clientSuitInfo, &serverSuitInfo, recordCtx->readStates.pendingState, recordCtx->writeStates.pendingState); recordCtx->readStates.pendingState = readState; recordCtx->writeStates.pendingState = writeState; return HITLS_SUCCESS; ERR: /* Clear sensitive information */ FreeDataAndState(&clientSuitInfo, &serverSuitInfo, readState, writeState); BSL_ERR_PUSH_ERROR(ret); return ret; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t REC_TLS13InitPendingState(const TLS_Ctx *ctx, const REC_SecParameters *param, bool isOut) { if (ctx == NULL || ctx->recCtx == NULL || param == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15542, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: ctx null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnSuitInfo suitInfo = {0}; RecConnState *state = RecConnStateNew(); if (state == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17305, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StateNew fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } /* 1.Generate a secret */ int32_t ret = RecTLS13ConnKeyBlockGen(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), param, &suitInfo); if (ret != HITLS_SUCCESS) { RecConnStateFree(state); return ret; } /* 2.Set the corresponding read/write pending state */ RecConnStates *curState = NULL; if (isOut) { curState = &(recordCtx->writeStates); } else { curState = &(recordCtx->readStates); } ret = RecConnStateSetCipherInfo(state, &suitInfo); if (ret != HITLS_SUCCESS) { RecConnStateFree(state); return ret; } RecConnStateFree(curState->pendingState); curState->pendingState = state; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t REC_ActivePendingState(TLS_Ctx *ctx, bool isOut) { RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnStates *states = (isOut == true) ? &recordCtx->writeStates : &recordCtx->readStates; if (states->pendingState == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15543, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: pending state should not be null.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } RecConnStateFree(states->outdatedState); states->outdatedState = states->currentState; states->currentState = states->pendingState; states->pendingState = NULL; RecConnSetSeqNum(states->currentState, 0); #ifdef HITLS_TLS_PROTO_DTLS12 if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { if (isOut) { ++recordCtx->writeEpoch; RecConnSetEpoch(states->currentState, recordCtx->writeEpoch); } else { ++recordCtx->readEpoch; RecConnSetEpoch(states->currentState, recordCtx->readEpoch); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) RecAntiReplayReset(&states->currentState->window); #endif } } #endif /* HITLS_TLS_PROTO_DTLS12 */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15544, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "Record: active pending state.", 0, 0, 0, 0); return HITLS_SUCCESS; } static uint32_t REC_GetRecordSizeLimitWriteLen(const TLS_Ctx *ctx) { uint32_t defaultLen = #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT (uint32_t)ctx->config.tlsConfig.maxSendFragment == 0 ? REC_MAX_PLAIN_TEXT_LENGTH : (uint32_t)ctx->config.tlsConfig.maxSendFragment; #else REC_MAX_PLAIN_TEXT_LENGTH; #endif if (ctx->negotiatedInfo.recordSizeLimit != 0 && ctx->negotiatedInfo.peerRecordSizeLimit <= defaultLen) { defaultLen = ctx->negotiatedInfo.peerRecordSizeLimit; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { defaultLen--; } } return defaultLen; } int32_t REC_RecOutBufReSet(TLS_Ctx *ctx) { RecCtx *recCtx = ctx->recCtx; return RecBufResize(recCtx->outBuf, RecGetWriteBufferSize(ctx)); } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static int32_t ChangeBufferSize(TLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; if (ctx->bUio == NULL) { ctx->mtuModified = false; return HITLS_SUCCESS; } uint32_t bufferLen = (uint32_t)ctx->config.pmtu; if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { ret = BSL_UIO_Ctrl(ctx->bUio, BSL_UIO_SET_BUFFER_SIZE, sizeof(uint32_t), &bufferLen); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17363, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "SET_BUFFER_SIZE fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_UIO_FAIL); return HITLS_UIO_FAIL; } } ctx->mtuModified = false; return HITLS_SUCCESS; } int32_t REC_QueryMtu(TLS_Ctx *ctx) { if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { return HITLS_SUCCESS; } uint16_t originMtu = ctx->config.pmtu; if (ctx->config.linkMtu > 0) { uint8_t overhead = 0; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_GET_MTU_OVERHEAD, sizeof(uint8_t), &overhead); ctx->config.pmtu = ctx->config.linkMtu - (uint16_t)overhead; ctx->config.linkMtu = 0; } if (ctx->needQueryMtu && !ctx->noQueryMtu) { uint32_t mtu = 0; int32_t ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_QUERY_MTU, sizeof(uint32_t), &mtu); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17364, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "UIO_Ctrl fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_UIO_FAIL); return HITLS_UIO_FAIL; } uint8_t overhead = 0; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_GET_MTU_OVERHEAD, sizeof(uint8_t), &overhead); uint16_t minMtu = (uint16_t)DTLS_MIN_MTU - (uint16_t)overhead; mtu = mtu > UINT16_MAX ? UINT16_MAX : mtu; ctx->config.pmtu = ((uint16_t)mtu < minMtu) ? minMtu : (uint16_t)mtu; } ctx->needQueryMtu = false; if (ctx->config.pmtu != originMtu || ctx->mtuModified) { return ChangeBufferSize(ctx); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ int32_t REC_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len) { if (ctx == NULL || ctx->recCtx == NULL || len == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15545, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Record: input null pointer.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *len = REC_GetRecordSizeLimitWriteLen(ctx); #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) uint32_t mtuLen = 0; int32_t ret = REC_GetMaxDataMtu(ctx, &mtuLen); if (ret == HITLS_SUCCESS) { *len = (*len > mtuLen) ? mtuLen : *len; } if (ret != HITLS_UIO_IO_TYPE_ERROR) { return ret; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t REC_GetMaxDataMtu(const TLS_Ctx *ctx, uint32_t *len) { bool isUdp = false; RecCtx *recordCtx = (RecCtx *)ctx->recCtx; RecConnState *currentState = recordCtx->writeStates.currentState; uint32_t overHead; BSL_UIO *uio = ctx->uio; while (uio != NULL) { if (BSL_UIO_GetUioChainTransportType(uio, BSL_UIO_UDP)) { isUdp = true; break; } uio = BSL_UIO_Next(uio); } if (!isUdp) { /* In non-UDP scenarios, there is no PMTU limit */ return HITLS_UIO_IO_TYPE_ERROR; } /* In UDP scenarios, handshake packets and application data packets with miniaturization enabled have the MTU limit */ uint32_t encryptLen = RecGetCryptoFuncs(currentState->suiteInfo)->calCiphertextLen(ctx, currentState->suiteInfo, 0, false); overHead = REC_DTLS_RECORD_HEADER_LEN + encryptLen; if (ctx->config.pmtu <= overHead) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17306, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "pmtu too small", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_PMTU_TOO_SMALL); return HITLS_REC_PMTU_TOO_SMALL; } *len = ctx->config.pmtu - overHead; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ REC_Type REC_GetUnexpectedMsgType(TLS_Ctx *ctx) { return ctx->recCtx->unexpectedMsgType; } void RecClearAlertCount(TLS_Ctx *ctx, REC_Type recordType) { if (recordType != REC_TYPE_ALERT) { ALERT_ClearWarnCount(ctx); } return; }
2302_82127028/openHiTLS-examples_1508
tls/record/src/record.c
C
unknown
25,244
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef RECORD_H #define RECORD_H #include "tls.h" #include "rec.h" #include "rec_header.h" #include "rec_unprocessed_msg.h" #include "rec_buf.h" #include "rec_conn.h" #ifdef __cplusplus extern "C" { #endif #define REC_MAX_PLAIN_TEXT_LENGTH 16384 /* Plain content length */ #define REC_MAX_ENCRYPTED_OVERHEAD 2048u /* Maximum Encryption Overhead rfc5246 */ #define REC_MAX_READ_ENCRYPTED_OVERHEAD REC_MAX_ENCRYPTED_OVERHEAD #define REC_MAX_WRITE_ENCRYPTED_OVERHEAD REC_MAX_ENCRYPTED_OVERHEAD #define REC_MAX_CIPHER_TEXT_LEN (REC_MAX_PLAIN_LENGTH + REC_MAX_ENCRYPTED_OVERHEAD) /* Maximum ciphertext length */ #define REC_MAX_AES_GCM_ENCRYPTION_LIMIT 23726566u /* RFC 8446 5.5 Limits on Key Usage AES-GCM SHOULD under 2^24.5 */ typedef struct { RecConnState *outdatedState; RecConnState *currentState; RecConnState *pendingState; } RecConnStates; typedef int32_t (*REC_ReadFunc)(TLS_Ctx *, REC_Type, uint8_t *, uint32_t *, uint32_t); typedef int32_t (*REC_WriteFunc)(TLS_Ctx *, REC_Type, const uint8_t *, uint32_t); typedef struct { ListHead head; /* Linked list header */ bool isExistCcsMsg; /* Check whether CCS messages exist in the retransmission message queue */ REC_Type type; /* message type */ uint8_t *msg; /* message data */ uint32_t len; /* message length */ } RecRetransmitList; typedef struct RecCtx { RecBuf *inBuf; /* Buffer for reading data */ RecBuf *outBuf; /* Buffer for writing data */ RecConnStates readStates; RecConnStates writeStates; RecBufList *hsRecList; /* hs plaintext data cache */ RecBufList *appRecList; /* app plaintext data cache */ uint32_t emptyRecordCnt; /* Count of empty records */ #ifdef HITLS_TLS_PROTO_DTLS12 uint16_t writeEpoch; uint16_t readEpoch; RecRetransmitList retransmitList; /* Cache the messages that may be retransmitted during the handshake */ /* Process out-of-order messages */ UnprocessedHsMsg unprocessedHsMsg; /* used to cache out-of-order finished messages */ /* unprocessed app message: app messages received in the CCS and finished receiving phases */ UnprocessedAppMsg unprocessedAppMsgList; #endif REC_ReadFunc recRead; void *rUserData; REC_WriteFunc recWrite; void *wUserData; REC_Type unexpectedMsgType; uint32_t pendingDataSize; /* Data length */ const uint8_t *pendingData; /* Plain Data content */ } RecCtx; /** * @brief Obtain the size of the buffer for read and write operations * * @param ctx [IN] TLS_Ctx context * @param isRead [IN] is read buffer * * @retval the size of the buffer for read and write operations */ uint32_t RecGetInitBufferSize(const TLS_Ctx *ctx, bool isRead); int32_t RecDerefBufList(TLS_Ctx *ctx); void RecClearAlertCount(TLS_Ctx *ctx, REC_Type recordType); /** * @brief free the record buffer * * @param ctx [IN] TLS_Ctx context * @param isOut [IN] is out buffer or not */ void RecTryFreeRecBuf(TLS_Ctx *ctx, bool isOut); /** * @brief Init the record io buffer * * @param ctx [IN] TLS_Ctx context * @param recordCtx [IN] record context * @param isRead [IN] Init in buffer or not * * @retval HITLS_SUCCESS * @retval HITLS_MEMALLOC_FAIL malloc fail */ int32_t RecIoBufInit(TLS_Ctx *ctx, RecCtx *recordCtx, bool isRead); #ifdef __cplusplus } #endif #endif /* RECORD_H */
2302_82127028/openHiTLS-examples_1508
tls/record/src/record.h
C
unknown
4,034
//欢迎 void welcome(); //经理功能界面 void mfunctionalinterface(); //业务员功能界面 void sfunctionalinterface(); //经理基本信息管理界面 void mfunctionalinterface1(); //经理客户分配界面 void mfunctionalinterface2(); //经理客户分组管理界面 void mfunctionalinterface3(); //经理信息查询界面 void mfunctionalinterface4(); //经理信息排序界面 void mfunctionalinterface5(); //经理信息统计界面 void mfunctionalinterface6(); //经理通信记录分析界面 void mfunctionalinterface7(); //经理系统维护界面 void mfunctionalinterface8(); //业务员基本信息查询界面 void sfunctionalinterface1(); //业务员基本信息排序界面 void sfunctionalinterface2(); //业务员基本信息统计界面 void sfunctionalinterface3(); //业务员通信记录管理界面 void sfunctionalinterface4(); //业务员通讯记录分析界面 void sfunctionalinterface5(); //刘瑞鑫的函数声明 //创建部分 struct Node1* creat_note_customer(struct Node1* end_);//创建客户信息 struct Node2* creat_note_cliaison(struct Node2* end_);//创建客户联络员信息 struct Node3* creat_note_salesman(struct Node3* end_);//模糊查询 //查询部分 //1.客户 void search_customer(struct Node1* head); void search_customer_num(struct Node1* head,int n);//编号查找 void search_customer_name(struct Node1* head,char* a);//名称查找 void fuzzyquery_client(struct Node1* head1);//模糊查询 //2.客户联络员 void search_cliaison(struct Node2* head); void search_cliaison_num(struct Node2 * head,int n);//编号查找 void search_cliaison_name(struct Node2 * head,char* a);//名称查找 void fuzzyquery_cliaison(struct Node2* head1);//模糊查询 //3.业务员部分 void search_salesman(struct Node3* head); void search_salesman_num(struct Node3 * head,int n);//编号查找 void search_salesman_name(struct Node3 * head,char* a);//名称查找 void fuzzyquery_salesman(struct Node3* head1);//模糊查询 //修改部分 void exchange_customer(struct Node1* t);//修改客户信息 void exchange_cliaison(struct Node2* t);//修改客户联络员信息 void exchange_salesman(struct Node3* t);//修改业务员信息 //删除部分 struct Node3* delete_salesman(struct Node3 *head); struct Node2* delete_cliaison(struct Node2 *head); struct Node1* delete_customer(struct Node1* head); //简单展示(用作提醒简单的成员名称和编号) void show_customer(struct Node1* head); void show_cliasion(struct Node2* head); void show_salesman(struct Node3* head); //分配部分 //1.给业务员分配客户 void allocation(struct Node1* head,struct Node3* head_);//分配1 void give_salesman_customer(struct Node1* head,struct Node3* head_);//分配2 void show_salesman_clients(struct Node3* head_) ;//展示分配情况 void modify_salesman_customer(struct Node1* head, struct Node3* head_);//修改业务员所负责的客户 //2.给客户分配客户联络员 void allocation_customer_cliasion(struct Node1* head,struct Node2* head_);//分配1 void give_customer_cliaison(struct Node1* head,struct Node2* head_);//分配2 void show_clients_cliaison(struct Node1* head_);//显示给客户分配的客户联络员的部分 void modify_client_cliaison(struct Node2* head, struct Node1* head_);//修改客户的客户联络员 //分组部分 struct Node4* creat_group(struct Node4* end_,struct Node1* head_);//创建分组的链表 void show_group(struct Node4* head,struct Node1* head_);//简单展示分组信息 void search_Node4(struct Node4* head,struct Node1* head_);//查询分组的具体信息 void delete_group(struct Node4* head,struct Node1* head_);//删除分组链表的节点 void modify_group_content(struct Node4* head, struct Node1* customer_head); void add_member_to_group(struct Node4* group, struct Node1* customer_head); void remove_member_from_group(struct Node4* group); //赵鸿轩的函数声明 //排序部分 void clisort(struct Node1 *head1);//对客户信息进行排序 void insertClient(struct Node1 **head, struct client newClient);// 插入客户节点 void swap(struct Node1 *a, struct Node1 *b);// 交换两个客户节点 void sortByClientCount(struct Node1 *head);// 根据客户编号进行排序 void sortByClientArea(struct Node1 *head);// 根据客户所在区域进行排序 void sortByClientScale(struct Node1 *head);// 根据客户规模进行排序 void clsort(struct Node2* head2); //对客户联络员信息排序 void salsort(struct Node3* head3);//对业务员信息排序 //统计部分 void cliareasinglestatistic(struct Node1* head);//按区域对客户进行统计 void cliscalesinglestatistic(struct Node1* head);//按规模对客户进行统计 void clilevelsinglestatistic(struct Node1* head);//按联系程度对客户进行统计 void climultistatistic(struct Node1* head1);//按规模和联系程度对客户进行统计 void cliconditionquery(struct Node1* head1);//条件统计查找客户的联络员数量 void displaygroupclientcount(struct Node4* head);//对指定分组下客户数量进行统计 void clistatistics(struct Node1 *head,struct Node4* head_cusgroup);//统计客户信息 void clstatistics(struct Node2 *head);//统计客户联络员数量 void salstatistics(struct Node3 *head);//统计业务员数量 //计林敏的函数声明 //密码维护 void pwmaintenance(char mpw[],char spw[]); //数据备份; void datebackup(struct Node1* np1,struct Node2* np2,struct Node3* np3); //数据恢复 void recoverydata(struct Node1* p1,struct Node2* p2,struct Node3* p3); //简单查找 void simplequery(struct Node1* head1); //组合查找 void combinedquery(struct Node1* head1); //模糊查找 void fuzzyquery(struct Node1* head1); //条件查找 void conditionquery(struct Node1* head1); //单一排序 void singlesort(struct Node1* head1); //多属性排序 void combinsort(struct Node1* head1); //单一统计 void singlestatistic(struct Node1* head1); //多属性统计 void multistatistic(struct Node1* head1); //预设统计 void defaultstatistic(struct Node1* head1);//预设条件统计高规模客户数 //条件统计 void conditionquery(struct Node1* head1);//条件统计查找客户的联络员数量 //王兴家的函数声明 int verify(char *kk);//验证 void Set_Salesman_passsword(char *password);//设置
2303_806435pww/tongxin
declaration.h
C
unknown
6,340
#include"tool.h" #include"declaration.h" void welcome()//欢迎 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信管理系统\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择您的身份:\t\t\t*\n"); printf("*\t\t1.公司经理\t\t\t*\n"); printf("*\t\t2.公司业务员\t\t\t*\n"); printf("*\t\t0.退出系统\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface()//经理功能界面函数 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信管理系统\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.基本信息管理\t\t\t*\n"); printf("*\t\t2.客户分配管理\t\t\t*\n"); printf("*\t\t3.客户分组管理\t\t\t*\n"); printf("*\t\t4.基本信息排序\t\t\t*\n"); printf("*\t\t5.基本信息统计\t\t\t*\n"); printf("*\t\t6.通信记录分析\t\t\t*\n"); printf("*\t\t7.系统维护\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface1()//经理基本信息管理界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息管理功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.录入业务员信息\t\t*\n"); printf("*\t\t2.录入客户基本信息\t\t*\n"); printf("*\t\t3.录入客户联络员信息\t\t*\n"); printf("*\t\t4.修改和查找业务员信息\t\t*\n"); printf("*\t\t5.修改和查找客户基本信息\t*\n"); printf("*\t\t6.修改和查找客户联络员信息\t*\n"); printf("*\t\t7.删除业务员信息\t\t*\n"); printf("*\t\t8.删除客户基本信息\t\t*\n"); printf("*\t\t9.删除客户联络员信息\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface2()//经理客户分配界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用客户分配功能\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.业务员分配客户\t\t*\n"); printf("*\t\t2.显示业务员客户\t\t*\n"); printf("*\t\t3.修改业务员客户\t\t*\n"); printf("*\t\t4.客户分配客户联络员\t\t*\n"); printf("*\t\t5.显示客户的客户联络员\t\t*\n"); printf("*\t\t6.修改客户客户联络员\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface3()//经理客户分组管理界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用客户分组管理功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.新建客户分组\t\t\t*\n"); printf("*\t\t2.查找分组\t\t\t*\n"); printf("*\t\t3.修改分组\t\t\t*\n"); printf("*\t\t4.删除分组\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface5()//经理信息排序界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息排序功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.排序业务员信息\t\t*\n"); printf("*\t\t2.排序客户信息\t\t\t*\n"); printf("*\t\t3.排序客户联络员信息\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface6()//经理信息统计界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息统计功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.统计业务员数量\t\t*\n"); printf("*\t\t2.统计客户数量\t\t\t*\n"); printf("*\t\t3.统计客户联络员数量\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface7()//经理通信记录分析界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信记录分析功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.查询通信情况\t\t\t*\n"); printf("*\t\t2.排序通信情况\t\t\t*\n"); printf("*\t\t3.统计通信情况\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface8()//经理系统维护界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用系统维护功能\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.密码维护\t\t\t*\n"); printf("*\t\t2.数据备份\t\t\t*\n"); printf("*\t\t3.数据恢复\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void sfunctionalinterface()//业务员功能界面函数 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信管理系统\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\
2303_806435pww/tongxin
f.c
C
unknown
6,168
#include"tool.h" #include"declaration.h" void welcome()//欢迎 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信管理系统\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择您的身份:\t\t\t*\n"); printf("*\t\t1.公司经理\t\t\t*\n"); printf("*\t\t2.公司业务员\t\t\t*\n"); printf("*\t\t0.退出系统\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface()//经理功能界面函数 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信管理系统\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.基本信息管理\t\t\t*\n"); printf("*\t\t2.客户分配管理\t\t\t*\n"); printf("*\t\t3.客户分组管理\t\t\t*\n"); printf("*\t\t4.基本信息排序\t\t\t*\n"); printf("*\t\t5.基本信息统计\t\t\t*\n"); printf("*\t\t6.通信记录分析\t\t\t*\n"); printf("*\t\t7.系统维护\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface1()//经理基本信息管理界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息管理功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.录入业务员信息\t\t*\n"); printf("*\t\t2.录入客户基本信息\t\t*\n"); printf("*\t\t3.录入客户联络员信息\t\t*\n"); printf("*\t\t4.修改和查找业务员信息\t\t*\n"); printf("*\t\t5.修改和查找客户基本信息\t*\n"); printf("*\t\t6.修改和查找客户联络员信息\t*\n"); printf("*\t\t7.删除业务员信息\t\t*\n"); printf("*\t\t8.删除客户基本信息\t\t*\n"); printf("*\t\t9.删除客户联络员信息\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface2()//经理客户分配界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用客户分配功能\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.业务员分配客户\t\t*\n"); printf("*\t\t2.显示业务员客户\t\t*\n"); printf("*\t\t3.修改业务员客户\t\t*\n"); printf("*\t\t4.客户分配客户联络员\t\t*\n"); printf("*\t\t5.显示客户的客户联络员\t\t*\n"); printf("*\t\t6.修改客户客户联络员\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface3()//经理客户分组管理界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用客户分组管理功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.新建客户分组\t\t\t*\n"); printf("*\t\t2.查找分组\t\t\t*\n"); printf("*\t\t3.修改分组\t\t\t*\n"); printf("*\t\t4.删除分组\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface5()//经理信息排序界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息排序功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.排序业务员信息\t\t*\n"); printf("*\t\t2.排序客户信息\t\t\t*\n"); printf("*\t\t3.排序客户联络员信息\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface6()//经理信息统计界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息统计功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.统计业务员数量\t\t*\n"); printf("*\t\t2.统计客户数量\t\t\t*\n"); printf("*\t\t3.统计客户联络员数量\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface7()//经理通信记录分析界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信记录分析功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.查询通信情况\t\t\t*\n"); printf("*\t\t2.排序通信情况\t\t\t*\n"); printf("*\t\t3.统计通信情况\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void mfunctionalinterface8()//经理系统维护界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用系统维护功能\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.密码维护\t\t\t*\n"); printf("*\t\t2.数据备份\t\t\t*\n"); printf("*\t\t3.数据恢复\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void sfunctionalinterface()//业务员功能界面函数 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信管理系统\t\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.基本信息查询\t\t\t*\n"); printf("*\t\t2.基本信息排序\t\t\t*\n"); printf("*\t\t3.基本信息统计\t\t\t*\n"); printf("*\t\t4.通信记录管理\t\t\t*\n"); printf("*\t\t5.通信记录分析\t\t\t*\n"); printf("*\t\t6.系统维护\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void sfunctionalinterface1()//业务员基本信息查询界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息查询功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.简单查询\t\t\t*\n"); printf("*\t\t2.组合查询\t\t\t*\n"); printf("*\t\t3.模糊查询\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void sfunctionalinterface2()//业务员基本信息排序界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息排序功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.简单排序\t\t\t*\n"); printf("*\t\t2.组合排序\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void sfunctionalinterface3()//业务员基本信息统计界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用基本信息统计功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.单属性统计\t\t\t*\n"); printf("*\t\t2.多属性统计\t\t\t*\n"); printf("*\t\t3.预设统计\t\t\t*\n"); printf("*\t\t4.条件统计\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void sfunctionalinterface4()//业务员通信记录管理界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信记录管理功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.增加通信情况\t\t\t*\n"); printf("*\t\t2.修改通信情况\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } void sfunctionalinterface5()//业务员通讯记录分析界面 { printf("*************************************************\n"); printf("*\t\t欢迎使用通信记录分析功能\t*\n"); printf("*************************************************\n"); printf("*\t\t请选择功能列表:\t\t\t*\n"); printf("*\t\t1.查询通信情况\t\t\t*\n"); printf("*\t\t2.排序通信情况\t\t\t*\n"); printf("*\t\t3.统计通信情况\t\t\t*\n"); printf("*\t\t0.返回上一界面\t\t\t*\n"); printf("*************************************************\n"); } //刘瑞鑫的函数定义 struct Node1* creat_note_customer(struct Node1* end_)//创建客户的链表节点 { struct Node1* fresh = (struct Node1*)malloc(sizeof(struct Node1)); fresh->pnext1 = NULL; end_->pnext1 = fresh; for(int i = 0 ; i < 20 ; i++) { fresh->headcliaison[i] = NULL; } printf("请输入客户编号(数字):"); while (1) { if(scanf("%d",&fresh->cli.clicount)!=1||fresh->cli.clicount<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } printf("请输入客户姓名:"); while(1) { scanf("%12s",fresh->cli.cliname); if(strlen(fresh->cli.cliname)>10) { printf("您输入的客户姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入客户所在区域:"); while(1) { scanf("%10s",fresh->cli.cliarea); if(strlen(fresh->cli.cliarea)>8) { printf("您输入的客户所在区域过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入客户所在地址:"); while(1) { scanf("%30s",fresh->cli.cliaddress); if(strlen(fresh->cli.cliaddress)>28) { printf("您输入的客户所在地址过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入客户法人姓名:"); while(1) { scanf("%12s",fresh->cli.clilegalman); if(strlen(fresh->cli.clilegalman)>10) { printf("您输入的客户法人姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入客户规模(大,中,小):"); while(1) { scanf("%3s",fresh->cli.cliscale); if(strcmp(fresh->cli.cliscale,"大")==0||strcmp(fresh->cli.cliscale,"中")==0||strcmp(fresh->cli.cliscale,"小")==0) { break; } else if(strlen(fresh->cli.cliscale)>1) { printf("您输入的客户规模过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } printf("请输入客户联系程度(高,中,低):"); while(1) { scanf("%3s",fresh->cli.cliconlevel); if(strcmp(fresh->cli.cliconlevel,"高")==0||strcmp(fresh->cli.cliconlevel,"中")==0||strcmp(fresh->cli.cliconlevel,"低")==0) { break; } else if(strlen(fresh->cli.cliconlevel)>1) { printf("您输入的客户联系程度过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } printf("请输入客户邮箱:"); while(1) { scanf("%15s",fresh->cli.climailbox); if(strlen(fresh->cli.climailbox)>13) { printf("您输入的客户邮箱过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入客户电话号码个数:"); while (1) { if(scanf("%d",&fresh->cli.clitelcount)!=1||fresh->cli.clitelcount<0||fresh->cli.clitelcount>10) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } for(int i = 0 ; i < fresh->cli.clitelcount ; i++) { printf("%d:",i + 1); while(1) { scanf("%13s",fresh->cli.clitel[i]); if(strlen(fresh->cli.clitel[i])>11) { printf("您输入的客户电话号码过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } } end_ = fresh; return end_; } struct Node2* creat_note_cliaison(struct Node2* end_)//创建客户联络员的链表节点 { struct Node2* fresh = (struct Node2*)malloc(sizeof(struct Node2)); fresh->pnext2 = NULL; end_-> pnext2 = fresh; printf("请输入客户联络员编号(数字):"); while (1) { if(scanf("%d",&fresh->cli.clcount)!=1||fresh->cli.clcount<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } printf("请输入客户联络员姓名:"); while(1) { scanf("%12s",fresh->cli.clname); if(strlen(fresh->cli.clname)>10) { printf("您输入的客户联络员姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入客户联络性别(男,女):"); while(1) { scanf("%s",fresh->cli.clsex); if(strcmp(fresh->cli.clsex,"女")==0||strcmp(fresh->cli.clsex,"男")==0) { break; } else if(strlen(fresh->cli.clsex)>1) { printf("您输入的客户联络员性别过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请重新输入:\n"); } } printf("请输入客户联络员生日:"); while(1) { scanf("%12s",fresh->cli.clbirthday); if(strlen(fresh->cli.clbirthday)>10) { printf("您输入的客户联络员生日过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入客户联络员邮箱:"); while(1) { scanf("%15s",fresh->cli.clmailbox); if(strlen(fresh->cli.clmailbox)>13) { printf("您输入的客户联络员邮箱过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("客户联络员电话号码个数:"); while (1) { if(scanf("%d",&fresh->cli.cltelcount)!=1||fresh->cli.cltelcount<0||fresh->cli.cltelcount>10) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } for(int i = 0 ; i < fresh->cli.cltelcount ; i++) { printf("%d:",i + 1); while(1) { scanf("%13s",fresh->cli.cltel[i]); if(strlen(fresh->cli.cltel[i])>11) { printf("您输入的客户电话号码过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } } end_ = fresh; return end_; } struct Node3* creat_note_salesman(struct Node3* end_)//创建业务员的链表节点 { struct Node3* fresh = (struct Node3*)malloc(sizeof(struct Node3)); fresh->pnext3 = NULL; end_->pnext3 = fresh; int num = 0; printf("请输入业务员编号(数字):"); while (1) { if(scanf("%d",&fresh->sal.scount)!=1||fresh->sal.scount<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } printf("请输入业务员姓名:"); while(1) { scanf("%12s",fresh->sal.sname); if(strlen(fresh->sal.sname)>10) { printf("您输入的业务员姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入业务员性别(男,女):"); while(1) { scanf("%s",fresh->sal.ssex); if(strcmp(fresh->sal.ssex,"女")==0||strcmp(fresh->sal.ssex,"男")==0) { break; } else if(strlen(fresh->sal.ssex)>1) { printf("您输入的客户联络员性别过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请重新输入:\n"); } } printf("请输入业务员生日:"); while(1) { scanf("%12s",fresh->sal.sbirthday); if(strlen(fresh->sal.sbirthday)>10) { printf("您输入的业务员员生日过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入业务员邮箱:"); while(1) { scanf("%15s",fresh->sal.smailbocx); if(strlen(fresh->sal.smailbocx)>13) { printf("您输入的业务员邮箱过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("业务员电话号码个数:"); while (1) { if(scanf("%d",&fresh->sal.stelcount)!=1||fresh->sal.stelcount<0||fresh->sal.stelcount>10) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } for(int i = 0 ; i < fresh->sal.stelcount ; i++) { printf("%d:",i + 1); while(1) { scanf("%13s",fresh->sal.stel[i]); if(strlen(fresh->sal.stel[i])>11) { printf("您输入的业务员电话号码过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } } fresh->sal.saleclient_size = 0; end_ = fresh; return end_; } void show_cliasion(struct Node2* head)//简单显示客户联络员的姓名编号 { while(head->pnext2 != NULL) { printf("编号:%d 名字:",head->pnext2->cli.clcount); puts(head->pnext2->cli.clname); head = head->pnext2; } } void show_customer(struct Node1* head)//简单显示客户的姓名编号 { struct Node1* current = head->pnext1; while(current!=NULL) { printf("编号:%d 名字:",current->cli.clicount); puts(current->cli.cliname); current = current->pnext1; } } void show_salesman(struct Node3* head)//简单显示业务员的姓名编号 { while(head->pnext3!= NULL) { printf("编号:%d 名字:%s\n",head->pnext3->sal.scount,head->pnext3->sal.sname); head = head->pnext3; } } void search_customer(struct Node1* head)//查询具体基本信息的函数 { char name[12]; char n[3]; int m = 0; show_customer(head); printf("1.姓名查找\n"); printf("2.编号查找\n"); printf("3.模糊查询\n"); printf("输入其他数字退出"); printf("请输入客户编号(数字):"); while(1) { scanf("%2s",n); n[2]='\0'; if(strlen(n)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } system("cls"); if(n[0] == '1') { printf("请输入要查询的客户姓名:"); while(1) { scanf("%12s",name); if(strlen(name)>10) { printf("您输入的客户姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } search_customer_name(head,name); } if(n[0] =='2') { printf("请输入要查询的客户的编号:"); while (1) { if(scanf("%d",&m)!=1||m<0) { printf("输入错误,请重新输入客户编号:\n"); while((getchar())!='\n'); continue; } else { break; } } search_customer_num(head,m); } if(n[0]=='3') { fuzzyquery_client(head->pnext1); } } void search_customer_num(struct Node1* head,int n)//通过编号来查询 { struct Node1 *t = head->pnext1; int time = 0; while (t!=NULL) { if(t->cli.clicount == n) { printf("客户编号:%d\n",t->cli.clicount); printf("客户姓名:"); puts(t->cli.cliname); printf("客户所在区域:"); puts(t->cli.cliarea); printf("客户所在地址:"); puts(t->cli.cliaddress); printf("客户法人:"); puts(t->cli.clilegalman); printf("客户规模:"); puts(t->cli.cliscale); printf("客户联系程度:"); puts(t->cli.cliconlevel); printf("客户邮箱:"); puts(t->cli.climailbox); time = 1; exchange_customer(t); } t = t->pnext1; } if(time == 0) { printf("没有此用户"); } system("pause"); } void search_customer_name(struct Node1* head,char* a)//通过姓名来查询 { struct Node1 *t = head->pnext1; int time = 0; while (t!=NULL) { if(strcmp(t->cli.cliname,a) == 0) { printf("客户编号:%d\n",t->cli.clicount); printf("客户姓名:"); puts(t->cli.cliname); printf("客户所在区域:"); puts(t->cli.cliarea); printf("客户所在地址:"); puts(t->cli.cliaddress); printf("客户法人:"); puts(t->cli.clilegalman); printf("客户规模:"); puts(t->cli.cliscale); printf("客户联系程度:"); puts(t->cli.cliconlevel); printf("客户邮箱:"); puts(t->cli.climailbox); time = 1; exchange_customer(t); } t = t->pnext1; } if(time == 0) { printf("没有此用户"); } system("pause"); } void search_cliaison(struct Node2* head)//查询具体基本信息的函数 { char name[10]; char n[3]; int m = 0; show_cliasion(head); printf("1.姓名查找\n"); printf("2.编号查找\n"); printf("3.模糊查询\n"); printf("输入其他数字退出\n"); printf("请输入客户编号(数字):"); while(1) { scanf("%2s",n); n[2]='\0'; if(strlen(n)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(n[0] == '1') { system("cls"); printf("请输入要查询的客户联络员姓名:"); while(1) { scanf("%12s",name); if(strlen(name)>10) { printf("您输入的客户联络员姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } search_customer_name(head,name); search_cliaison_name(head,name); } if(n[0] == '2') { system("cls"); printf("请输入要查询的客户联络员的编号:"); while (1) { if(scanf("%d",&m)!=1||m<0) { printf("输入错误,请重新输入客户联络员编号:\n"); while((getchar())!='\n'); continue; } else { break; } } scanf("%d",&m); search_cliaison_num(head,m); } if(n[0]=='3') { fuzzyquery_cliaison(head->pnext2); } } void search_cliaison_num(struct Node2 * head,int n)//通过编号来查询 { struct Node2* t = head->pnext2; int time = 0; while (t!=NULL) { if(t->cli.clcount == n) { printf("客户联络员编号:%d\n",t->cli.clcount); printf("客户联络员姓名:"); puts(t->cli.clname); printf("客户联络员性别:"); puts(t->cli.clsex); printf("客户联络员生日:"); puts(t->cli.clbirthday); printf("客户联络员邮箱:"); puts(t->cli.clmailbox); time = 1; exchange_cliaison(t); } t = t->pnext2; } if(time == 0) { printf("没有此业务联络员"); } system("pause"); } void search_cliaison_name(struct Node2 * head,char* a)//通过姓名来查询 { struct Node2* t = head->pnext2; int time = 0; while (t!=NULL) { if(strcmp(t->cli.clname,a) == 0) { printf("客户联络员编号:%d\n",t->cli.clcount); printf("客户联络员姓名:"); puts(t->cli.clname); printf("客户联络员性别:"); puts(t->cli.clsex); printf("客户联络员生日:"); puts(t->cli.clbirthday); printf("客户联络员邮箱:"); puts(t->cli.clmailbox); time = 1; exchange_cliaison(t); } t = t->pnext2; } if(time == 0) { printf("没有此业务联络员"); } system("pause"); } void search_salesman(struct Node3* head)//查询具体基本信息的函数 { char name[10]; char n[3]; int m = 0; show_salesman(head); printf("1.姓名查找\n"); printf("2.编号查找\n"); printf("3.模糊查询\n"); printf("输入其他数字退出"); while(1) { scanf("%2s",n); n[2]='\0'; if(strlen(n)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(n[0] == '1') { system("cls"); printf("请输入要查询的业务员姓名:"); while(1) { scanf("%12s",name); if(strlen(name)>10) { printf("您输入的业务员姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } search_salesman_name(head,name); } if(n[0] == '2') { system("cls"); printf("请输入要查询业务员的编号:"); while (1) { if(scanf("%d",&m)!=1||m<0) { printf("输入错误,请重新输入客户联络员编号:\n"); while((getchar())!='\n'); continue; } else { break; } } search_salesman_num(head,m); } if(n[0]=='3') { fuzzyquery_salesman(head->pnext3); } } void search_salesman_num(struct Node3 * head,int n)//通过编号来查询 { struct Node3* t = head->pnext3; int time = 0; while (t!=NULL) { if(t->sal.scount == n) { printf("业务员编号:%d\n",t->sal.scount); printf("业务员姓名:"); puts(t->sal.sname); printf("业务员性别:"); puts(t->sal.ssex); printf("业务员生日:"); puts(t->sal.sbirthday); printf("业务员邮箱:"); puts(t->sal.smailbocx); time = 1; exchange_salesman(t); } t = t->pnext3; } if(time == 0) { printf("没有此业务员!\n"); } system("pause"); } void search_salesman_name(struct Node3 * head,char* a)//通过姓名来查询 { struct Node3* t = head->pnext3; int time = 0; while (t!=NULL) { if(strcmp(t->sal.sname,a) == 0) { printf("业务员编号:%d\n",t->sal.scount); printf("业务员姓名:"); puts(t->sal.sname); printf("业务员性别:"); puts(t->sal.ssex); printf("业务员生日:"); puts(t->sal.sbirthday); printf("业务员邮箱:"); puts(t->sal.smailbocx); time = 1; exchange_salesman(t); } t = t->pnext3; } if(time == 0) { printf("没有此业务员!\n"); } system("pause"); } void fuzzyquery_client(struct Node1* head1)//模糊查询客户 { char ncliname[12]; int i; printf("请输入要查找的客户姓名的关键字:\n"); while(1) { scanf("%12s",ncliname); if(strlen(ncliname)>10) { printf("您输入的客户姓名关键字过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } struct Node1*p=head1; if(p==NULL) { printf("未查询到该顾客信息!\n"); } while(p!=NULL) { if(strstr (p->cli.cliname,ncliname)!=NULL)//用于在一个字符串中查找另一个字符首次出现,找到了返回在其首次出现位置的指针,没有返回NULL { printf("客户编号:%d\n",p->cli.clicount); printf("客户姓名:"); puts(p->cli.cliname); printf("客户所在区域:"); puts(p->cli.cliarea); printf("客户所在地址:"); puts(p->cli.cliaddress); printf("客户法人:"); puts(p->cli.clilegalman); printf("客户规模:"); puts(p->cli.cliscale); printf("客户联系程度:"); puts(p->cli.cliconlevel); printf("客户邮箱:"); puts(p->cli.climailbox); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); exchange_customer(p); } p=p->pnext1; } system("pause"); system("cls"); } void fuzzyquery_cliaison(struct Node2* head1)//模糊查询客户联络员 { char ncliname[12]; int i; printf("请输入要查找的客户联络员姓名的关键字:\n"); while(1) { scanf("%12s",ncliname); if(strlen(ncliname)>10) { printf("您输入的客户联络员姓名关键字过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } struct Node2*p=head1; if(p==NULL) { printf("未查询到该顾客信息!\n"); } while(p!=NULL) { if(strstr (p->cli.clname,ncliname)!=NULL)//用于在一个字符串中查找另一个字符首次出现,找到了返回在其首次出现位置的指针,没有返回NULL { printf("客户联络员编号:%d\n",p->cli.clcount); printf("客户联络员姓名:"); puts(p->cli.clname); printf("客户联络员性别:"); puts(p->cli.clsex); printf("客户联络员生日:"); puts(p->cli.clbirthday); printf("客户联络员邮箱:"); puts(p->cli.clmailbox); for(i=0;i<p->cli.cltelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.cltel[i]); } printf("\n"); exchange_cliaison(p); } p=p->pnext2; } system("pause"); system("cls"); } void fuzzyquery_salesman(struct Node3* head1)//模糊查询业务员 { char ncliname[12]; int i; printf("请输入要查找的业务员姓名的关键字:\n"); while(1) { scanf("%12s",ncliname); if(strlen(ncliname)>10) { printf("您输入的客户姓名关键字过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } struct Node3*p=head1; if(p==NULL) { printf("未查询到该顾客信息!\n"); } while(p!=NULL) { printf("业务员编号:%d\n",p->sal.scount); printf("业务员姓名:"); puts(p->sal.sname); printf("业务员性别:"); puts(p->sal.ssex); printf("业务员生日:"); puts(p->sal.sbirthday); printf("业务员邮箱:"); puts(p->sal.smailbocx); for(i=0;i<p->sal.stelcount;i++) { printf("电话号码%d:%s ",i+1,p->sal.stel[i]); } printf("\n"); exchange_salesman(p); p=p->pnext3; } system("pause"); system("cls"); } void exchange_customer(struct Node1* t)//在查询后进行修改(客户) { printf("是否进行修改 1-是,2-否"); char n[3],m[3]; int end_ = 0; while(1) { scanf("%2s",n); n[2]='\0'; if(strlen(n)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(n[0] == '1') { printf("1.客户编号 "); printf("2.客户姓名 "); printf("3.客户所在区域 "); printf("4.客户所在地址 "); printf("5.客户法人 "); printf("6.客户规模 "); printf("7.客户联系程度 "); printf("8.客户邮箱 "); printf("0.退出\n"); while(end_ == 0) { printf("请输入修改的项: "); while(1) { scanf("%2s",m); m[2]='\0'; if(strlen(m)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } switch(m[0]) { case '1' : printf("请输入更改后结果: "); scanf("%d",&t->cli.clicount); printf("客户修改成功!\n"); break; case '2' : printf("请输入更改后结果: "); scanf("%s",&t->cli.cliname); printf("客户姓名修改成功!\n"); break; case '3' : printf("请输入更改后结果: "); scanf("%s",&t->cli.cliarea); printf("客户所在区域修改成功!\n"); break; case '4' : printf("请输入更改后结果: "); scanf("%s",&t->cli.cliaddress); printf("客户所在地址修改成功!\n"); break; case '5' : printf("请输入更改后结果: "); scanf("%s",&t->cli.clilegalman); printf("客户法人修改成功!\n"); break; case '6' : printf("请输入更改后结果: "); scanf("%d",&t->cli.cliscale); printf("客户规模修改成功!\n"); break; case '7' : printf("请输入更改后结果: "); scanf("%s",&t->cli.cliconlevel); printf("客户联系程度修改成功!\n"); break; case '8' : printf("请输入更改后结果: "); scanf("%s",&t->cli.climailbox); printf("客户邮箱修改成功!\n"); break; case '0' : end_ = 1; break; default : break; } } } } void exchange_cliaison(struct Node2* t)//在查询后进行修改(客户联络员) { printf("是否进行修改 1-是,2-否"); char n[3]; char m[3]; int end_; while(1) { scanf("%2s",n); n[2]='\0'; if(strlen(n)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(n[0] == '1') { printf("1.客户联络员编号"); printf("2.客户联络员姓名"); printf("3.客户联络员性别"); printf("4.客户联络员生日"); printf("5.客户联络员邮箱"); printf("0.退出"); while(end_ == 0) { printf("请输入要更改的项: "); while(1) { scanf("%2s",m); m[2]='\0'; if(strlen(m)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } switch(m[0]) { case '1' : printf("请输入更改后结果: "); scanf("%d",&t->cli.clcount); printf("客户联络员编号修改成功!\n"); break; case '2' : printf("请输入更改后结果: "); scanf("%s",&t->cli.clname); printf("客户联络员姓名修改成功!\n"); break; case '3' : printf("请输入更改后结果: "); scanf("%s",&t->cli.clsex); printf("客户联络员性别修改成功!\n"); break; case '4' : printf("请输入更改后结果: "); scanf("%s",&t->cli.clbirthday); printf("客户联络员生日修改成功!\n"); break; case '5' : printf("请输入更改后结果: "); scanf("%s",&t->cli.clmailbox); printf("客户联络员邮箱修改成功!\n"); break; case '0' : end_ = 1; break; default: break; } } } } void exchange_salesman(struct Node3* t)//在查询后进行修改(业务员) { printf("是否进行修改 1-是,2-否"); char n[3]; char m[3]; int end_ = 0; while(1) { scanf("%2s",n); n[2]='\0'; if(strlen(n)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(n[0]== '1') { printf("1.业务员编号"); printf("2.业务员姓名"); printf("3.业务员性别"); printf("4.业务员生日"); printf("5.业务员邮箱"); printf("0.退出"); while(end_ == 0) { printf("请输入要更改的项: "); while(1) { scanf("%2s",m); m[2]='\0'; if(strlen(m)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } switch(m[0]) { case '1' : printf("请输入更改后结果: "); scanf("%d",&t->sal.scount); printf("业务员编号修改成功!\n"); break; case '2' : printf("请输入更改后结果: "); scanf("%s",&t->sal.sname); printf("业务员姓名修改成功!\n"); break; case '3' : printf("请输入更改后结果: "); scanf("%s",&t->sal.ssex); printf("业务员性别修改成功!\n"); break; case '4' : printf("请输入更改后结果: "); scanf("%s",&t->sal.sbirthday); printf("业务员生日修改成功!\n"); break; case '5' : printf("请输入更改后结果: "); scanf("%s",&t->sal.smailbocx); printf("业务员邮箱修改成功!\n"); break; case '0' : end_ = 1; break; default: break; } } } } struct Node1* delete_customer(struct Node1 *head)//删除客户节点 { show_customer(head); printf("请输入要删除的节点的编号:"); int cli_count = 0; while (1) { if(scanf("%d",&cli_count)!=1||cli_count<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } struct Node1 *current = head; struct Node1 *prev = NULL; int found = 0; // 遍历链表查找要删除的节点 while (current != NULL) { if (current->cli.clicount == cli_count) { found = 1; break; } prev = current; current = current->pnext1; } if (found) { // 如果找到了要删除的节点 if (prev == NULL) { // 删除的是头节点 head = current->pnext1; } else { // 删除的不是头节点 prev->pnext1 = current->pnext1; } // 释放被删除节点的内存 free(current); } else { printf("没有找到编号为 %d 的客户\n", cli_count); } return head; // 返回更新后的头节点 } struct Node2* delete_cliaison(struct Node2 *head)//删除客户联络员节点 { show_cliasion(head); printf("请输入要删除的节点的编号:"); int cl_count = 0; while (1) { if(scanf("%d",&cl_count)!=1||cl_count<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } struct Node2 *current = head; struct Node2 *prev = NULL; int found = 0; // 遍历链表查找要删除的节点 while (current != NULL) { if (current->cli.clcount == cl_count) { found = 1; break; } prev = current; current = current->pnext2; } if (found) { // 如果找到了要删除的节点 if (prev == NULL) { // 删除的是头节点 head = current->pnext2; } else { // 删除的不是头节点 prev->pnext2 = current->pnext2; } // 释放被删除节点的内存 free(current); } else { printf("没有找到编号为 %d 的业务联络员\n", cl_count); } return head; // 返回更新后的头节点 } struct Node3* delete_salesman(struct Node3 *head)//删除业务员节点 { show_salesman(head); printf("请输入要删除的节点的编号:"); int scount = 0; while (1) { if(scanf("%d",&scount)!=1||scount<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } struct Node3 *current = head; struct Node3 *prev = NULL; int found = 0; // 遍历链表查找要删除的节点 while (current != NULL) { if (current->sal.scount == scount) { found = 1; break; } prev = current; current = current->pnext3; } if (found) { // 如果找到了要删除的节点 if (prev == NULL) { // 删除的是头节点 head = current->pnext3; } else { // 删除的不是头节点 prev->pnext3 = current->pnext3; } // 释放被删除节点的内存 free(current); } else { printf("没有找到编号为 %d 的业务员\n", scount); } return head; // 返回更新后的头节点 } //赵鸿轩的函数定义 void clsort(struct Node2* head2) //对客户联络员信息排序 { if (head2 == NULL) { printf("输入链表为空!\n"); return; } struct Node2* p = head2; struct Node2* t = NULL; struct Node2* cur = p->pnext2; struct Node2* prev = head2; struct Node2* end = NULL; int i; int swap = 0; p = head2; printf("请选择排序方式\n"); printf("1-按联络员姓名进行排序\n"); printf("2-按联络员编号进行排序\n"); char sortType = getch(); printf("请选择升降序:\n"); printf("1-升序 2-降序\n"); char sortorder = getch(); while (cur != end) { swap = 0; while (cur->pnext2 != end) { if (sortType == '1') { if ((sortorder == '1' && strcmp(cur->cli.clname, cur->pnext2->cli.clname) > 0) || (sortorder == '2' && strcmp(cur->cli.clname, cur->pnext2->cli.clname) < 0)) { t = cur->pnext2->pnext2; prev->pnext2 = cur->pnext2; cur->pnext2->pnext2 = cur; cur->pnext2 = t; prev = prev->pnext2; swap = 1; } else { prev = cur; cur = cur->pnext2; } } else if (sortType == '2') { if ((sortorder == '1' && cur->cli.clcount > cur->pnext2->cli.clcount) || (sortorder == '2' && cur->cli.clcount < cur->pnext2->cli.clcount)) { t = cur->pnext2->pnext2; prev->pnext2 = cur->pnext2; cur->pnext2->pnext2 = cur; cur->pnext2 = t; prev = prev->pnext2; swap = 1; } else { prev = cur; cur = cur->pnext2; } } } if (swap == 0) { break; } end = cur; prev = p; cur = p->pnext2; } p = head2->pnext2; while (p != NULL) { printf("联络员编号:%d 联络员姓名:%s 联络员性别:%s 联络员生日:%s 联络员邮箱:%s 电话号码数量:%d ", p->cli.clcount, p->cli.clname, p->cli.clsex, p->cli.clbirthday, p->cli.clmailbox, p->cli.cltelcount); for (i = 0; i < p->cli.cltelcount; i++) { printf("电话号码%d:%s ", i + 1, p->cli.cltel[i]); } printf("\n"); p = p->pnext2; } system("pause"); } void salsort(struct Node3* head3)//对业务员信息排序 { if (head3 == NULL) { printf("输入链表为空!\n"); return; } struct Node3* p = head3; struct Node3* t = NULL; struct Node3* cur = p->pnext3; struct Node3* prev = head3; struct Node3* end = NULL; int i; int swap = 0; p = head3; printf("请选择排序方式\n"); printf("1-按业务员姓名进行排序\n"); printf("2-按业务员编号进行排序\n"); char sortType = getch(); printf("请选择升降序:\n"); printf("1-升序 2-降序\n"); char sortorder = getch(); while (cur != end) { swap = 0; while (cur->pnext3 != end) { if (sortType == '1') { if ((sortorder == '1' && strcmp(cur->sal.sname, cur->pnext3->sal.sname) > 0) || (sortorder == '2' && strcmp(cur->sal.sname, cur->pnext3->sal.sname) < 0)) { t = cur->pnext3->pnext3; prev->pnext3 = cur->pnext3; cur->pnext3->pnext3 = cur; cur->pnext3 = t; prev = prev->pnext3; swap = 1; } else { prev = cur; cur = cur->pnext3; } } else if (sortType == '2') { if ((sortorder == '1' && cur->sal.scount > cur->pnext3->sal.scount) || (sortorder == '2' && cur->sal.scount < cur->pnext3->sal.scount)) { t = cur->pnext3->pnext3; prev->pnext3 = cur->pnext3; cur->pnext3->pnext3 = cur; cur->pnext3 = t; prev = prev->pnext3; swap = 1; } else { prev = cur; cur = cur->pnext3; } } } if (swap == 0) { break; } end = cur; prev = p; cur = p->pnext3; } p = head3->pnext3; while (p != NULL) { printf("业务员编号:%d 业务员姓名:%s 业务员性别:%s 业务员生日:%s 业务员邮箱:%s 电话号码数量:%d ", p->sal.scount, p->sal.sname, p->sal.ssex, p->sal.sbirthday, p->sal.smailbocx, p->sal.stelcount); for (i = 0; i < p->sal.stelcount; i++) { printf("电话号码%d:%s ", i + 1, p->sal.stel[i]); } printf("\n"); p = p->pnext3; } system("pause"); } void cliareasinglestatistic(struct Node1* head)//按区域对客户进行统计 { struct Node1*p=head; char narea[10]; int count=0; printf("请输入要统计的区域:\n"); while(1) { scanf("%10s",narea); //检测输入区域 if(strlen(narea)>9) { printf("您输入的客户所在区域过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } while(p!=NULL) { if(strcmp(p->cli.cliarea,narea)==0) { count+=1; } p=p->pnext1; } printf("%s区域的客户人数为:%d\n",narea,count); system("pause"); } void cliscalesinglestatistic(struct Node1* head)//按规模对客户进行统计 { struct Node1*p=head; char nscale[3]; int count=0; int i; printf("请输入客户规模(大,中,小):"); while(1) { scanf("%3s",nscale); //检测输入规模 if(strcmp(nscale,"大")==0||strcmp(nscale,"中")==0||strcmp(nscale,"小")==0) { break; } else if(strlen(nscale)>2) { printf("您输入的客户规模过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } while(p!=NULL) { if(strcmp(p->cli.cliscale,nscale)==0) { count+=1; } p=p->pnext1; } printf("%s规模的客户人数为:%d\n",nscale,count); system("pause"); } void clilevelsinglestatistic(struct Node1* head)//按联系程度对客户进行统计 { struct Node1*p=head; char nlevel[3]; int count=0; int i; printf("请输入客户联系程度(高,中,低):"); while(1) { scanf("%3s",nlevel); //检测输入联系程度 if(strcmp(nlevel,"高")==0||strcmp(nlevel,"中")==0||strcmp(nlevel,"低")==0) { break; } else if(strlen(nlevel)>2) { printf("您输入的客户联系程度过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } while(p!=NULL) { if(strcmp(p->cli.cliconlevel,nlevel)==0) { count+=1; } p=p->pnext1; } printf("%s联系程度的客户人数为:%d\n",nlevel,count); system("pause"); } void climultistatistic(struct Node1* head1)//按规模和联系程度对客户进行统计 { struct Node1*p=head1; int count=0; int i; char nscale[3]; char nlevel[3]; printf("请输入客户规模(大,中,小):"); while(1) { scanf("%3s",nscale); if(strcmp(nscale,"大")==0||strcmp(nscale,"中")==0||strcmp(nscale,"小")==0) { break; } else if(strlen(nscale)>2) { printf("您输入的客户规模过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } printf("请输入客户联系程度(高,中,低):"); while(1) { scanf("%3s", nlevel); if(strcmp( nlevel,"高")==0||strcmp( nlevel,"中")==0||strcmp( nlevel,"低")==0) { break; } else if(strlen( nlevel)>2) { printf("您输入的客户联系程度过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } while(p!=NULL) { if(strcmp(p->cli.cliscale,nscale)==0&&strcmp(p->cli.cliconlevel,nlevel)==0) { count+=1; } p=p->pnext1; } printf("客户规模为%s和客户联系程度为%s的人数为:%d\n",nscale,nlevel,count); system("pause"); } void cliconditionquery(struct Node1* head1)//条件统计查找客户的联络员数量 { char ncliname[14]; printf("请输入客户姓名:\n"); scanf("%s",ncliname); struct Node1*p1=head1; int n = 0; while(p1!=NULL) { if(strcmp (p1->cli.cliname,ncliname)==0) { n = 1; break; } p1=p1->pnext1; } if(n == 0) { printf("无此客户信息!\n"); system("pause"); } else { int count = 0; for (int i = 0; i < p1->cliaison_size; i++) { struct Node2* p2 = p1->headcliaison[i]; while (p2 != NULL) { count += 1; p2 = p2->pnext2; } } printf("该客户的联络员数量为%d\n", count); system("pause"); } } void displaygroupclientcount(struct Node4* head)//对指定分组下客户数量进行统计 { struct Node4* current = head->pnext4; int found = 0;//添加一个标志表示是否找到分组 char groupName[12]; printf("请输入组名\n"); scanf("%s",groupName); if(strlen(groupName)>12) { printf("组名过长!请重新输入\n"); while((getchar())!='\n'); } while (current != NULL) { if (strcmp(current->crgroup.cusname,groupName) == 0) { printf("分组名称: %s\n", current->crgroup.cusname); printf("客户数量: %d\n", current->crgroup.size_); found = 1; return; } current = current->pnext4; } if (!found) // 如果未找到匹配的分组 { printf("未找到分组 '%s'\n", groupName); } system("pause"); } void clistatistics(struct Node1 *head,struct Node4* head_cusgroup)//统计客户信息 { int clicount = 0; int targetcliaison =0; int targetclient = 0; struct Node1 *current = head->pnext1; struct Node4* headgroup = NULL; if (head == NULL) { printf("无法进行统计\n"); system("pause"); system("cls"); return; } printf("请选择统计方式\n"); printf("1-统计客户数量\n"); printf("2-统计指定区域客户数量\n"); printf("3-统计指定规模客户数量\n"); printf("4-统计指定联系程度客户数量\n"); printf("5-统计指定规模及联系程度的客户数量\n"); printf("6-统计指定客户所有联络员数量\n"); printf("7-统计指定分组下客户数量\n"); printf("0-返回上一界面\n"); while (1) { char sortType=getch(); switch(sortType) { case '1': while (current != NULL) { clicount++; current = current->pnext1; } printf("客户有%d位\n",clicount); system("pause"); break; case '2': { cliareasinglestatistic(head); break; } case '3': { cliscalesinglestatistic(head); break; } case '4': { clilevelsinglestatistic(head); break; } case '5': { climultistatistic(head); break; } case '6': { cliconditionquery(head); break; } case '7': { displaygroupclientcount(head_cusgroup); break; } case '0': { break; } default: { printf("输入错误,请重新输入!\n"); system("pause"); break; } } if(sortType=='0') { system("cls"); break; } } } void clstatistics(struct Node2 *head)//统计客户联络员数量 { int clcount = 0; struct Node2 *current2 = head->pnext2; if (head == NULL) { printf("无法进行统计\n"); return; } while (current2 != NULL) { clcount++; current2 = current2->pnext2; } printf("客户联络员有%d位\n",clcount); system("pause"); } void salstatistics(struct Node3 *head)//统计业务员数量 { int salcount = 0; struct Node3 *current = head->pnext3; if (head == NULL) { printf("无法进行统计\n"); system("pause"); return; } while (current != NULL) { salcount++; current = current->pnext3; } printf("业务员有%d位\n",salcount); system("pause"); } void clisort(struct Node1 *head1) { struct Node1*p=head1->pnext1; int i; printf("请选择排序方式\n"); printf("1-根据客户编号进行排序\n"); printf("2-根据客户所在区域进行排序\n"); printf("3-根据客户规模进行排序\n"); printf("4-先根据客户所在区域进行排序,后根据客户编号进行排序\n"); printf("5-先根据客户规模进行排序,后根据客户编号进行排序\n"); char sortType=getch(); switch(sortType) { case '1': sortByClientCount(head1->pnext1); while(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); p=p->pnext1; } system("pause"); system("cls"); break; case '2': sortByClientArea(head1->pnext1); while(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); p=p->pnext1; } system("pause"); system("cls"); break; case '3': sortByClientScale(head1->pnext1); while(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); p=p->pnext1; } system("pause"); system("cls"); break; case '4': sortByClientArea(head1->pnext1); sortByClientCount(head1->pnext1); while(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); p=p->pnext1; } system("pause"); system("cls"); break; case '5': sortByClientScale(head1->pnext1); sortByClientCount(head1->pnext1); while(p != NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); p = p->pnext1; } system("pause"); system("cls"); break; } } // 插入客户节点 void insertClient(struct Node1 **head, struct client newClient) { struct Node1 *newNode = (struct Node1 *)malloc(sizeof(struct Node1)); newNode->cli = newClient; newNode->pnext1 = *head; *head = newNode; } // 交换两个客户节点 void swap(struct Node1 *a, struct Node1 *b) { struct client temp = a->cli; a->cli = b->cli; b->cli = temp; } // 根据客户编号进行排序 void sortByClientCount(struct Node1 *head) { int swapped; struct Node1 *ptr1 = NULL; struct Node1 *lptr = NULL; /* 检查链表是否为空 */ if (head == NULL) return; do { swapped = 0; ptr1 = head; while (ptr1->pnext1 != lptr) { if (ptr1->cli.clicount > ptr1->pnext1->cli.clicount) { swap(ptr1, ptr1->pnext1); swapped = 1; } ptr1 = ptr1->pnext1; } lptr = ptr1; } while (swapped); } // 根据客户所在区域进行排序 void sortByClientArea(struct Node1 *head) { int swapped; struct Node1 *ptr1; struct Node1 *lptr = NULL; /* 检查链表是否为空 */ if (head == NULL) return; do { swapped = 0; ptr1 = head; while (ptr1->pnext1 != lptr) { if (strcmp(ptr1->cli.cliarea, ptr1->pnext1->cli.cliarea) > 0) { swap(ptr1, ptr1->pnext1); swapped = 1; } ptr1 = ptr1->pnext1; } lptr = ptr1; } while (swapped); } // 根据客户规模进行排序 void sortByClientScale(struct Node1 *head) { int swapped; struct Node1 *ptr1; struct Node1 *lptr = NULL; /* 检查链表是否为空 */ if (head == NULL) return; do { swapped = 0; ptr1 = head; while (ptr1->pnext1 != lptr) { if (ptr1->cli.cliscale > ptr1->pnext1->cli.cliscale) { swap(ptr1, ptr1->pnext1); swapped = 1; } ptr1 = ptr1->pnext1; } lptr = ptr1; } while (swapped); } //计林敏的函数定义 void pwmaintenance(char mpw[],char spw[])//密码维护 { char nmpw[14],nnmpw[14],nspw[14],nnspw[14]; char i[3]; printf("1.修改经理密码 2.修改业务员密码 3.重置经理密码 4.重置业务员密码 0.退出密码维护功能\n请输入您要执行的操作:"); while(1) { while(1) { scanf("%2s",i); i[2]='\0'; if(strlen(i)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(i[0]=='1') { printf("请输入您的12位以内的新密码:\n"); while(1) { while(1) { scanf("%13s",nmpw); nmpw[13]='\0'; if(strlen(nmpw)>12) { printf("您输入的密码过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请再次输入您的12位以内新密码:\n"); while(1) { scanf("%13s",nnmpw); nnmpw[13]='\0'; if(strlen(nnmpw)>12) { printf("您输入的密码过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(strcmp(nmpw,nnmpw)==0) { strcpy(mpw,nmpw); printf("您的密码修改成功!\n"); break; } else { printf("两次输入的密码不一致,请重新输入您的12位以内的新密码:\n"); } } system("pause"); break; } else if(i[0]=='2') { printf("请输入业务员的12位以内的新密码:\n"); while(1) { while(1) { scanf("%13s",nspw); nmpw[13]='\0'; if(strlen(nspw)>12) { printf("您输入的密码过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请再次输入您的12位以内新密码:\n"); while(1) { scanf("%13s",nnspw); nnmpw[13]='\0'; if(strlen(nnspw)>12) { printf("您输入的密码过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(strcmp(nspw,nnspw)==0) { strcpy(spw,nspw); printf("您的密码修改成功!\n"); break; } else { printf("两次输入的密码不一致,请重新输入您的12位以内的新密码:\n"); } } system("pause"); break; } else if(i[0]=='3') { strcpy(mpw,"123456"); printf("您的密码重置成功!\n"); system("pause"); break; } else if(i[0]=='4') { strcpy(spw,"123456"); printf("业务员的密码重置成功!\n"); system("pause"); break; } else if(i[0]=='0') { break; } else { printf("您的输入有误,请重新输入:\n"); } } } void datebackup(struct Node1* np1,struct Node2* np2,struct Node3* np3)//数据备份 { struct Node1* p1=np1->pnext1; struct Node2* p2=np2->pnext2; struct Node3* p3=np3->pnext3; char i[3]; int j; printf("1.备份客户数据 2.备份客户联络员数据 3.备份业务员数据 0.退出数据备份功能\n请选择要执行的操作:"); while(1) { while(1) { scanf("%2s",i); i[2]='\0'; if(strlen(i)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(i[0]=='1') { //打开文件 FILE *fp= fopen("C:\\customer.data","w");//写入,如果文件不存在创建文件,文件存在清空内容再写入 if(fp==NULL) { printf("打开文件失败!\n"); perror("错误原因:");//显示错误原因 system("pause"); break; } if(p1==NULL) { printf("您没有客户数据可备份!\n"); system("pause"); break; } while(p1!=NULL) { fprintf(fp,"客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d ", p1->cli.clicount,p1->cli.cliname,p1->cli.cliarea,p1->cli.cliaddress, p1->cli.clilegalman,p1->cli.cliscale,p1->cli.cliconlevel,p1->cli.climailbox, p1->cli.clitelcount); for(j=0;j<p1->cli.clitelcount;j++) { fprintf(fp,"客户电话号码%d:%s ",j+1,p1->cli.clitel[j]); } fprintf(fp,"\n"); p1=p1->pnext1; } fclose(fp);//释放对该文件的占用,避免数据丢失 printf("客户数据备份成功!\n"); system("pause"); break; } else if(i[0]=='2') { //打开文件 FILE *fp= fopen("C:\\cliaison.data","w"); if(fp==NULL) { printf("打开文件失败!\n"); perror("错误原因:");//显示错误原因 system("pause"); break; } if(p2==NULL) { printf("您没有客户联络员数据可备份!\n"); system("pause"); break; } while(p2!=NULL) { fprintf(fp,"联络员编号:%d 联络员姓名:%s 联络员性别:%s 联络员生日:%s 联络员邮箱:%s 联络员电话号码数量:%d ", p2->cli.clcount,p2->cli.clname,p2->cli.clsex,p2->cli.clbirthday,p2->cli.clmailbox,p2->cli.cltelcount); for(j=0;j<p2->cli.cltelcount;j++) { fprintf(fp,"联络员电话号码%d:%s ",j+1,p2->cli.cltel[j]); } fprintf(fp,"\n"); p2=p2->pnext2; } fclose(fp); printf("客户联络员数据备份成功!\n"); system("pause"); break; } else if(i[0]=='3') { //打开文件 FILE *fp= fopen("C:\\salesman.data","w"); if(fp==NULL) { printf("打开文件失败!\n"); perror("错误原因:");//显示错误原因 system("pause"); break; } if(p3==NULL) { printf("您没有业务员数据可备份!\n"); system("pause"); break; } while(p3!=NULL) { fprintf(fp,"业务员编号:%d 业务员姓名:%s 业务员性别:%s 业务员生日:%s 业务员邮箱:%s 业务员电话号码数量:%d ", p3->sal.scount,p3->sal.sname,p3->sal.ssex,p3->sal.sbirthday,p3->sal.smailbocx,p3->sal.stelcount ); for(j=0;j<p3->sal.stelcount;j++) { fprintf(fp,"业务员电话号码%d:%s ",j+1,p3->sal.stel[j]); } fprintf(fp,"\n"); p3=p3->pnext3; } fclose(fp); printf("业务员数据备份成功!\n"); system("pause"); break; } else if(i[0]=='0') { break; } else { printf("您的输入有误,请重新输入:\n"); } } } void recoverydata(struct Node1* p1,struct Node2* p2,struct Node3* p3)//数据恢复 { char i[3]; int j; printf("1.恢复客户数据 2.恢复客户联络员数据 3.恢复业务员数据 0.退出数据恢复功能\n请选择要执行的操作:"); while(1) { while(1) { scanf("%2s",i); i[2]='\0'; if(strlen(i)>1) { printf("您的输入有误,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } if(i[0]=='1') { //打开文件 FILE *fp= fopen("C:\\customer.data","r");//只读,不能进行修改 if(fp==NULL) { printf("打开文件失败!\n"); perror("错误原因:");//显示错误原因 system("pause"); break; } //feof(fp) 只有在尝试从文件中读取数据,并且读取操作到达文件末尾时,才会返回非零值(通常是 true)。 //所以循环不退出是因为feof()这个函数只有读到文件末尾才会返回true,而我是用feof()判断的,然后再读, //在循环中读到最后之后还要判断一次feof()但是循环中已经读不了数据了,此时feof()返回false,然后就会造成无限循环 while(!feof(fp)) { struct Node1 *np1=(struct Node1*)malloc(sizeof(struct Node1)); if(fscanf(fp,"客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d ", &np1->cli.clicount,np1->cli.cliname,np1->cli.cliarea,np1->cli.cliaddress, np1->cli.clilegalman,np1->cli.cliscale,np1->cli.cliconlevel,np1->cli.climailbox, &np1->cli.clitelcount)==EOF) { free(np1); break; } for(j=1;j<(np1->cli.clitelcount+1);j++) { fscanf(fp,"客户电话号码%d:%s ",&j,np1->cli.clitel[j-1]); } np1->pnext1=NULL; if(p1==NULL) { p1=np1; } else { while(p1->pnext1!=NULL) { p1=p1->pnext1; } p1->pnext1=np1; } } fclose(fp); printf("客户数据恢复成功!\n"); system("pause"); break; } else if(i[0]=='2') { //打开文件 FILE *fp= fopen("C:\\cliaison.data","r"); if(fp==NULL) { printf("打开文件失败!\n"); perror("错误原因:");//显示错误原因 system("pause"); break; } while(!feof(fp)) { struct Node2 *np2=(struct Node2*)malloc(sizeof(struct Node2)); if(fscanf(fp,"联络员编号:%d 联络员姓名:%s 联络员性别:%s 联络员生日:%s 联络员邮箱:%s 联络员电话号码数量:%d ", &np2->cli.clcount, np2->cli.clname, np2->cli.clsex, np2->cli.clbirthday, np2->cli.clmailbox, &np2->cli.cltelcount)==EOF) { free(np2); break; } for(j=1;j<(np2->cli.cltelcount+1);j++) { fscanf(fp,"联络员电话号码%d:%s ",&j,np2->cli.cltel[j-1]); } np2->pnext2=NULL; if(p2==NULL) { p2=np2; } else { while(p2->pnext2!=NULL) { p2=p2->pnext2; } p2->pnext2=np2; } } fclose(fp); printf("客户联络员数据恢复成功!\n"); system("pause"); break; } else if(i[0]=='3') { //打开文件 FILE *fp= fopen("C:\\salesman.data","r"); if(fp==NULL) { printf("打开文件失败!\n"); perror("错误原因:");//显示错误原因 system("pause"); break; } while(!feof(fp)) { struct Node3 *np3=(struct Node3*)malloc(sizeof(struct Node3)); if(fscanf(fp,"业务员编号:%d 业务员姓名:%s 业务员性别:%s 业务员生日:%s 业务员邮箱:%s 业务员电话号码数量:%d ", &np3->sal.scount,np3->sal.sname,np3->sal.ssex,np3->sal.sbirthday,np3->sal.smailbocx,&np3->sal.stelcount )==EOF) { free(np3); break; } for(j=1;j<(np3->sal.stelcount+1);j++) { fscanf(fp,"业务员电话号码%d:%s ",&j,np3->sal.stel[j-1]); } np3->pnext3=NULL; if(p3==NULL) { p3=np3; } else { while(p3->pnext3!=NULL) { p3=p3->pnext3; } p3->pnext3=np3; } } fclose(fp); printf("业务员数据恢复成功!\n"); system("pause"); break; } else if(i[0]=='0') { break; } else { printf("您的输入有误,请重新输入:\n"); } } } void simplequery(struct Node1* head1)//简单查询 { char ncliname[12]; int i; printf("请输入要查找的客户姓名:\n"); while(1) { scanf("%12s",ncliname); if(strlen(ncliname)>10) { printf("您输入的客户姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } struct Node1*p=head1; while(p!=NULL) { if(strcmp (p->cli.cliname,ncliname)==0) { break; } p=p->pnext1; } if(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); } else { printf("未查询到该顾客信息!\n"); } system("pause"); system("cls"); } void combinedquery(struct Node1* head1)//组合查询 { char ncliname[12];//客户姓名 char ncliarea[10];//客户所在区域 char ncliaddress[30];//客户所在地址 int i; printf("请输入要查找的客户姓名:\n"); while(1) { scanf("%12s",ncliname); if(strlen(ncliname)>10) { printf("您输入的客户姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入要查找的客户所在区域:\n"); while(1) { scanf("%10s",ncliarea); if(strlen(ncliname)>8) { printf("您输入的客户所在区域过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } printf("请输入要查找的客户所在地址:\n"); while(1) { scanf("%30s",ncliaddress); if(strlen(ncliaddress)>28) { printf("您输入的客户所在地址过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } struct Node1*p=head1; while(p!=NULL) { if(strcmp (p->cli.cliname,ncliname)==0&&strcmp(p->cli.cliarea,ncliarea)==0&&strcmp (p->cli.cliaddress,ncliaddress)==0) { break; } p=p->pnext1; } if(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); } else { printf("未查询到该顾客信息!\n"); } system("pause"); system("cls"); } void fuzzyquery(struct Node1* head1)//模糊查询 { char ncliname[12]; int i; printf("请输入要查找的客户姓名的关键字:\n"); while(1) { scanf("%12s",ncliname); if(strlen(ncliname)>10) { printf("您输入的客户姓名关键字过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } struct Node1*p=head1; if(p==NULL) { printf("未查询到该顾客信息!\n"); } while(p!=NULL) { if(strstr (p->cli.cliname,ncliname)!=NULL)//用于在一个字符串中查找另一个字符首次出现,找到了返回在其首次出现位置的指针,没有返回NULL { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); } p=p->pnext1; } system("pause"); system("cls"); } void slightsort(struct Node1* head1)//单一排序 { if (head1 == NULL) { printf("输入链表为空!\n"); return; } struct Node1*p=head1; struct Node1*t=NULL;//避免野指针 struct Node1*cur=p->pnext1; struct Node1*prev=head1; struct Node1*end=NULL;//避免野指针 int i; int swap=0; while(p!=NULL) { if(strcmp(p->cli.cliscale,"大")==0) { p->cli.cliordernumber=3; } else if(strcmp(p->cli.cliscale,"中")==0) { p->cli.cliordernumber=2; } else { p->cli.cliordernumber=1; } p=p->pnext1; } //排序 p=head1; while(cur!=end) { swap=0; while(cur->pnext1!=end) { if(cur->cli.cliordernumber<cur->pnext1->cli.cliordernumber) { t=cur->pnext1->pnext1; prev->pnext1=cur->pnext1; cur->pnext1->pnext1=cur; cur->pnext1=t; prev=prev->pnext1; swap=1; } else { prev=cur; cur=cur->pnext1; } } if(swap==0) { break; } end=cur; prev=p; cur=p->pnext1; } p=head1->pnext1; while(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); p=p->pnext1; } system("pause"); system("cls"); } void combinsort(struct Node1* head1)//组合排序 { if (head1 == NULL) { printf("输入链表为空!\n"); return; } struct Node1*p=head1; struct Node1*t=NULL;//避免野指针 struct Node1*cur=p->pnext1; struct Node1*prev=head1;//避免野指针 struct Node1*end=NULL;//避免野指针 int i; int swap=0; while(p!=NULL) { if(strcmp(p->cli.cliscale,"大")==0&&strcmp(p->cli.cliconlevel,"高")==0) { p->cli.cliordernumber=9; } else if(strcmp(p->cli.cliscale,"大")==0&&strcmp(p->cli.cliconlevel,"中")==0) { p->cli.cliordernumber=8; } else if(strcmp(p->cli.cliscale,"大")==0&&strcmp(p->cli.cliconlevel,"低")==0) { p->cli.cliordernumber=7; } else if(strcmp(p->cli.cliscale,"中")==0&&strcmp(p->cli.cliconlevel,"高")==0) { p->cli.cliordernumber=6; } else if(strcmp(p->cli.cliscale,"中")==0&&strcmp(p->cli.cliconlevel,"中")==0) { p->cli.cliordernumber=5; } else if(strcmp(p->cli.cliscale,"中")==0&&strcmp(p->cli.cliconlevel,"低")==0) { p->cli.cliordernumber=4; } else if(strcmp(p->cli.cliscale,"小")==0&&strcmp(p->cli.cliconlevel,"高")==0) { p->cli.cliordernumber=3; } else if(strcmp(p->cli.cliscale,"小")==0&&strcmp(p->cli.cliconlevel,"中")==0) { p->cli.cliordernumber=2; } else { p->cli.cliordernumber=1; } p=p->pnext1; } //排序 p=head1; while(cur!=end) { swap=0; while(cur->pnext1!=end) { if(cur->cli.cliordernumber<cur->pnext1->cli.cliordernumber) { t=cur->pnext1->pnext1; prev->pnext1=cur->pnext1; cur->pnext1->pnext1=cur; cur->pnext1=t; prev=prev->pnext1; swap=1; } else { prev=cur; cur=cur->pnext1; } } if(swap==0) { break; } end=cur; prev=p; cur=p->pnext1; } p=head1->pnext1; while(p!=NULL) { printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); p=p->pnext1; } system("pause"); system("cls"); } void singlestatistic(struct Node1* head1)//单一统计 { struct Node1*p=head1; char narea[10]; int count=0; int i; printf("请输入要统计的区域:\n"); while(1) { scanf("%10s",narea); if(strlen(narea)>8) { printf("您输入的客户所在区域过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } while(p!=NULL) { if(strcmp(p->cli.cliarea,narea)==0) { count+=1; printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); } p=p->pnext1; } printf("%s区域的客户人数为:%d\n",narea,count); system("pause"); system("cls"); } void multistatistic(struct Node1* head1)//多属性统计 { struct Node1*p=head1; int count=0; int i; char nscale[3]; char nlevel[3]; printf("请输入客户规模(大,中,小):"); while(1) { scanf("%3s",nscale); if(strcmp(nscale,"大")==0||strcmp(nscale,"中")==0||strcmp(nscale,"小")==0) { break; } else if(strlen(nscale)>1) { printf("您输入的客户规模过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } printf("请输入客户联系程度(高,中,低):"); while(1) { scanf("%3s", nlevel); if(strcmp( nlevel,"高")==0||strcmp( nlevel,"中")==0||strcmp( nlevel,"低")==0) { break; } else if(strlen( nlevel)>1) { printf("您输入的客户联系程度过长,请重新输入:\n"); while((getchar())!='\n'); } else { printf("您的输入有误,请按规定重新输入:\n"); } } while(p!=NULL) { if(strcmp(p->cli.cliscale,nscale)==0&&strcmp(p->cli.cliconlevel,nlevel)==0) { count+=1; printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); } p=p->pnext1; } printf("客户规模为%s和客户联系程度为%s的人数为:%d\n",nscale,nlevel,count); system("pause"); system("cls"); } void defaultstatistic(struct Node1* head1)//预设条件统计高规模客户数 { struct Node1*p=head1; int count=0; int i; while(p!=NULL) { if(strcmp(p->cli.cliscale,"大")==0) { count+=1; printf("客户编号:%d 客户姓名:%s 客户所在区域:%s 客户所在地址:%s 客户法人:%s 客户规模:%s 客户联系程度:%s 客户邮箱:%s 客户电话号码数量:%d " ,p->cli.clicount,p->cli.cliname,p->cli.cliarea,p->cli.cliaddress, p->cli.clilegalman,p->cli.cliscale,p->cli.cliconlevel,p->cli.climailbox,p->cli.clitelcount); for(i=0;i<p->cli.clitelcount;i++) { printf("电话号码%d:%s ",i+1,p->cli.clitel[i]); } printf("\n"); } p=p->pnext1; } printf("高规模的客户人数为%d\n",count); system("pause"); system("cls"); } void conditionquery(struct Node1* head1)//条件统计查找客户的联络员数量 { char ncliname[12]; int i,j,count; printf("请输入您要查找某一客户的联络员数量的客户姓名:\n"); while(1) { scanf("%12s",ncliname); if(strlen(ncliname)>10) { printf("您输入的客户姓名过长,请重新输入:\n"); while((getchar())!='\n'); } else { break; } } struct Node1*p1=head1; while(p1!=NULL) { if(strcmp (p1->cli.cliname,ncliname)==0) { break; } p1=p1->pnext1; } if(p1==NULL) { printf("无此客户信息!\n"); system("pause"); system("cls"); } else { for(i=0;p1->headcliaison[i]!=NULL;i++) { count+=1; printf(" 客户联络员编号:%d 客户联络员姓名:%s 客户联络员性别:%s 客户联络员生日:%s 客户联络员邮箱:%s 客户联络员电话号码数量", p1->headcliaison[i]->cli.clcount,p1->headcliaison[i]->cli.clname,p1->headcliaison[i]->cli.clsex,p1->headcliaison[i]->cli.clbirthday ,p1->headcliaison[i]->cli.clmailbox,p1->headcliaison[i]->cli.cltelcount); for(j=0;j<p1->headcliaison[i]->cli.cltelcount;j++) { printf("电话号码数%d:%s",j+1,p1->headcliaison[i]->cli.cltel[j]); } printf("\n"); } printf("该客户的联络员数量为%d\n",count); system("pause"); system("cls"); } } //王兴家的函数定义 int verify(char *kk)//验证 { char sss[20]; scanf("%s", sss); if (strcmp(sss, kk) == 0) return 1; else return 0; } void Set_Salesman_passsword(char *password)//设置 { char new_password[20]; char confirm_password[20]; printf("请输入新的销售人员密码:\n"); scanf("%s", new_password); printf("请再次输入新的销售人员密码以确认:\n"); scanf("%s", confirm_password); if (strcmp(new_password, confirm_password) == 0) { strcpy(password, new_password); printf("销售人员密码设置成功!\n"); } else { printf("两次输入的密码不匹配,请重新设置销售人员密码!\n"); } } //清空输入缓冲区 void clearInputBuffer() { while (getchar() != '\n') ; } //安全读取字符串 void safeReadString(char *str, int size) { int success = 0; while (!success) { if (scanf("%19s", str) == 1) { // 假设字符串大小为20 success = 1; } else { printf("输入错误,请重新输入:"); clearInputBuffer(); } } clearInputBuffer(); // 清除字符串后的换行符 } //安全读取整数 int safeReadInt() { int success = 0; char input[20]; while (!success) { if (scanf("%19s", input) == 1) { // 假设数字字符串大小为20 int valid = 1; for (int i = 0; i < strlen(input); i++) { if (!isdigit(input[i])) { valid = 0; break; } } if (valid) { success = 1; return atoi(input); } else { printf("输入错误,请重新输入:"); clearInputBuffer(); } } else { printf("输入错误,请重新输入:"); clearInputBuffer(); } } } //添加新记录 void addNewRecord(struct comcontent **head) { struct comcontent *newRecord = (struct comcontent *)malloc(sizeof(struct comcontent)); if (newRecord == NULL) { printf("内存分配失败!\n"); return; } printf("输入客户公司名称:"); safeReadString(newRecord->ccompny, 20); printf("输入客户联络员名称:"); safeReadString(newRecord->cclname, 20); printf("输入通信发生的年份:"); newRecord->year = safeReadInt(); printf("输入通信发生的月份:"); newRecord->month = safeReadInt(); printf("输入通信发生的日期:"); newRecord->day = safeReadInt(); printf("输入通信发生的小时:"); newRecord->hour = safeReadInt(); printf("输入通信持续时间(分钟):"); newRecord->duration = safeReadInt(); printf("输入通信内容:"); safeReadString(newRecord->contnt, 100); printf("输入通信类型:"); safeReadString(newRecord->comtype, 20); printf("输入通信次数:"); newRecord->comcount = safeReadInt(); // 写入文件 FILE *file = fopen("records.txt", "a"); if (file == NULL) { printf("无法打开文件!\n"); free(newRecord); return; } fprintf(file, "客户公司名称: %s\n", newRecord->ccompny); fprintf(file, "客户联络员名称: %s\n", newRecord->cclname); fprintf(file, "通信发生的时间: %d-%02d-%02d %02d:00\n", newRecord->year, newRecord->month, newRecord->day, newRecord->hour); fprintf(file, "通信持续时间(分钟): %d\n", newRecord->duration); fprintf(file, "通信内容: %s\n", newRecord->contnt); fprintf(file, "通信类型: %s\n", newRecord->comtype); fprintf(file, "通信次数: %d\n", newRecord->comcount); fprintf(file, "\n"); // 分隔每条记录 fclose(file); // 将记录添加到链表头部 newRecord->next = *head; *head = newRecord; printf("记录添加成功\n"); system("pause"); system("cls"); } //修改记录 void modifyRecord(struct comcontent **head) { char targetCompany[20]; printf("输入要修改通信记录的客户公司名称:"); safeReadString(targetCompany, 20); struct comcontent *current = *head; int found = 0; while (current != NULL) { if (strcmp(current->ccompny, targetCompany) == 0) { // 找到匹配的记录 found = 1; printf("找到匹配的通信记录!\n"); // 在这里编写修改信息的代码,例如: printf("请输入新的通信内容:"); safeReadString(current->contnt, 100); printf("通信内容已修改!\n"); } current = current->next; } if (!found) { // 若未找到匹配的记录 printf("未找到匹配的通信记录。\n"); } system("pause"); system("cls"); } //打印记录 void printAllRecords(struct comcontent **head) { if (*head == NULL) { printf("没有任何通信记录。\n"); } struct comcontent *current = *head; printf("所有通信记录:\n"); printf("------------------------------------------------------------------------\n"); printf("| %-20s | %-20s | %4s | %2s | %2s | %2s | %3s | %-20s | %-20s | %6s |\n", "客户公司名称", "客户联络员名称", "年份", "月份", "日期", "小时", "时长", "通信内容", "通信类型", "通信次数"); printf("------------------------------------------------------------------------\n"); while (current != NULL) { if(current->ccompny == NULL || current->cclname == NULL || current->contnt == NULL || current->comtype == NULL) { printf("错误:通信记录中存在空指针。\n"); break; // 直接终止函数 } printf("| %-20s | %-20s | %4d | %2d | %2d | %2d | %3d | %-20s | %-20s | %6d |\n", current->ccompny, current->cclname, current->year, current->month, current->day, current->hour, current->duration, current->contnt, current->comtype, current->comcount); current = current->next; } printf("-------------------------------------------------------------------------\n"); system("pause"); system("cls"); } //释放内存 void freeMemory(struct comcontent *head) { struct comcontent *current = head; while (current != NULL) { struct comcontent *next = current->next; free(current); current = next; } } //读文件 void addNewRecordFromFile(struct comcontent **head) { FILE *file = fopen("records.txt", "r"); if (file == NULL) { printf("无法打开文件!\n"); return; } while (!feof(file)) { struct comcontent *newRecord = (struct comcontent *)malloc(sizeof(struct comcontent)); if (newRecord == NULL) { printf("内存分配失败!\n"); fclose(file); return; } // 逐行读取文件中的记录 fscanf(file, "客户公司名称: %s\n", newRecord->ccompny); fscanf(file, "客户联络员名称: %s\n", newRecord->cclname); fscanf(file, "通信发生的时间: %d-%d-%d %d:00\n", &newRecord->year, &newRecord->month, &newRecord->day, &newRecord->hour); fscanf(file, "通信持续时间(分钟): %d\n", &newRecord->duration); // 读取通信内容,包括空格,直到遇到换行符 fscanf(file, "通信内容: "); fgets(newRecord->contnt, sizeof(newRecord->contnt), file); strtok(newRecord->contnt, "\n"); // 去除fgets末尾的换行符 // 读取通信类型,包括空格,直到遇到换行符 fscanf(file, "通信类型: "); fgets(newRecord->comtype, sizeof(newRecord->comtype), file); strtok(newRecord->comtype, "\n"); // 去除fgets末尾的换行符 fscanf(file, "通信次数: %d\n", &newRecord->comcount); newRecord->next = *head; *head = newRecord; } fclose(file); printf("文件录入成功\n"); system("pause"); system("cls"); } //按时间排序 void sortByTime(struct comcontent **head) { // 如果链表为空或只有一个节点,无需排序 if (*head == NULL || (*head)->next == NULL) { } // 创建一个新的空链表,用于存放已排序的节点 struct comcontent* sorted = NULL; struct comcontent* current = *head; // 遍历原链表的每个节点 while (current != NULL) { // 先将当前节点从原链表中取出 struct comcontent* next = current->next; current->next = NULL; // 将当前节点插入已排序的链表中 if (sorted == NULL || current->year > sorted->year || (current->year == sorted->year && current->month > sorted->month) || (current->year == sorted->year && current->month == sorted->month && current->day > sorted->day) || (current->year == sorted->year && current->month == sorted->month && current->day == sorted->day && current->hour > sorted->hour)) { // 如果当前节点时间比已排序节点的时间更晚,将其作为新的头部节点 current->next = sorted; sorted = current; } else { // 否则,在已排序链表中找到合适的位置插入当前节点 struct comcontent* temp = sorted; while (temp->next != NULL && (current->year < temp->next->year || (current->year == temp->next->year && current->month < temp->next->month) || (current->year == temp->next->year && current->month == temp->next->month && current->day < temp->next->day) || (current->year == temp->next->year && current->month == temp->next->month && current->day == temp->next->day && current->hour < temp->next->hour))) { temp = temp->next; } // 将当前节点插入temp节点后面 current->next = temp->next; temp->next = current; } // 继续处理下一个节点 current = next; } // 更新原链表的头指针 *head = sorted; system("pause"); system("cls"); } //统计链表中的信息函数 void countTotalStats(struct comcontent *head) { int totalCommunicationCount = 0; // 总通信次数 int totalYearCount = 0; // 总年份数量 int totalMonthCount = 0; // 总月份数量 int totalDateCount = 0; // 总日期数量 int totalHourCount = 0; // 总小时数量 // 遍历链表,累加统计信息 struct comcontent *current = head; while (current != NULL) { totalCommunicationCount += current->comcount; totalYearCount += current->year; totalMonthCount += current->month; totalDateCount += current->day; totalHourCount += current->hour; // 继续处理下一个节点 current = current->next; } // 打印统计信息(中文) printf("总通信次数: %d\n", totalCommunicationCount); printf("总年份数量: %d\n", totalYearCount); printf("总月份数量: %d\n", totalMonthCount); printf("总日期数量: %d\n", totalDateCount); printf("总小时数量: %d\n", totalHourCount); system("pause"); system("cls"); }
2303_806435pww/tongxin
function.c
C
unknown
108,524
#include"tool.h" #include"declaration.h" void allocation(struct Node1* head,struct Node3* head_)//给业务员分配客户的显示部分 { printf("客户简要信息\n"); show_customer(head); printf("业务员\n"); show_salesman(head_); give_salesman_customer(head,head_); } void give_salesman_customer(struct Node1* head,struct Node3* head_)//分配的修改部分 { struct Node3* t = head_->pnext3; int num = 0, time = 0; printf("请输入业务员编号:"); int n = 0; while (1) { if(scanf("%d",&n)!=1||n<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } while (t != NULL) { if (n == t->sal.scount) { do { printf("请输入所选客户的编号:"); printf("(输入0退出)"); scanf("%d", &num); if (num == 0) break; // 用户输入0时退出循环 struct Node1* p = head->pnext1; while (p != NULL) { if (p->cli.clicount == num) { if (time < 20) { // 确保不超出数组界限 t->sal.saleclient[time] = p; time++; t->sal.saleclient_size = time; break; // 找到匹配项后跳出内层循环 } else { printf("销售人员的客户列表已满。\n"); break; } } p = p->pnext1; } } while (num != 0); } t = t->pnext3; } } void show_salesman_clients(struct Node3* head_)//显示给业务员分配的客户的部分 { struct Node3* t = head_->pnext3; while (t != NULL) { printf("业务员编号: %d\n", t->sal.scount); for (int i = 0; i < t->sal.saleclient_size; i++) { printf("分配的客户编号,名字:"); if (t->sal.saleclient[i] != NULL) { printf("%d %s", t->sal.saleclient[i]->cli.clicount,t->sal.saleclient[i]->cli.cliname); } } printf("\n"); t = t->pnext3; } system("pause"); } void modify_salesman_customer(struct Node1* head, struct Node3* head_) { // 显示客户信息和业务员信息 printf("客户简要信息\n"); show_customer(head); printf("业务员\n"); show_salesman(head_); // 输入业务员编号 int salesman_num; printf("请输入要修改客户分配的业务员编号:"); scanf("%d", &salesman_num); // 查找对应业务员节点 struct Node3* current_salesman = head_->pnext3; while (current_salesman != NULL) { if (current_salesman->sal.scount == salesman_num) { // 输入要分配的客户编号 int client_num, time = 0; do { printf("请输入要分配给该业务员的客户编号:(输入0退出)"); scanf("%d", &client_num); if (client_num == 0) break; // 输入0退出循环 // 在客户链表中查找对应客户编号的客户节点 struct Node1* current_client = head->pnext1; while (current_client != NULL) { if (current_client->cli.clicount == client_num) { if (time < 20) { // 将客户添加到业务员的客户数组中 current_salesman->sal.saleclient[time] = current_client; time++; current_salesman->sal.saleclient_size = time; printf("客户编号为 %d 的客户分配给业务员编号为 %d 的业务员成功。\n", client_num, salesman_num); break; // 找到匹配项后跳出内层循环 } else { printf("业务员的客户列表已满。\n"); break; } } current_client = current_client->pnext1; } if (current_client == NULL) { printf("未找到编号为 %d 的客户。\n", client_num); } } while (client_num != 0); // 已找到对应业务员,不需要继续循环 break; } current_salesman = current_salesman->pnext3; } // 如果未找到对应业务员,输出提示信息 if (current_salesman == NULL) { printf("未找到编号为 %d 的业务员。\n", salesman_num); } } void allocation_customer_cliasion(struct Node1* head,struct Node2* head_)//给客户与联络员的链接的显示部分 { printf("客户简要信息\n"); show_customer(head); printf("业务联络员\n"); show_cliasion(head_); give_customer_cliaison(head,head_); } void give_customer_cliaison(struct Node1* head,struct Node2* head_)//分配的修改部分 { struct Node1* t = head->pnext1; int num = 0, time = 0; printf("请输入客户编号:"); int n = 0; while (1) { if(scanf("%d",&n)!=1||n<0) { printf("输入错误,请重新输入:\n"); while((getchar())!='\n'); continue; } else { break; } } while (t != NULL) { if (n == t->cli.clicount) {
2303_806435pww/tongxin
function2.c
C
unknown
5,824
#include"tool.h" #include "declaration.h" int main() { //初始密码 char pwman[14],pwslman[14]; char mpassward[14]; char spassward[14]; strcpy(pwman,"123456"); strcpy(pwslman,"123456"); struct Node1* head_customer = (struct Node1 *)malloc(sizeof(struct Node1));//创建表头 head_customer->pnext1 = NULL; struct Node1* end_customer = head_customer; struct Node2* head_cliaison = (struct Node2 *)malloc(sizeof(struct Node2));//创建表头 head_cliaison->pnext2 = NULL; struct Node2* end_cliaison = head_cliaison; struct Node3* head_salesman = (struct Node3 *)malloc(sizeof(struct Node3));//创建表头 head_salesman->pnext3 = NULL; struct Node3* end_salesman = head_salesman; struct Node4* head_group = (struct Node4 *)malloc(sizeof(struct Node4));//创建表头 head_group->pnext4 = NULL; struct Node4* end_group = head_group; struct comcontent *head = NULL;//声明一个指向通信内容的指针变量 while(1) { welcome();//欢迎界面函数 char ch=getch();//读取一个字符可以不按回车执行 if(ch=='1') { printf("请输入您的密码:\n"); scanf("%14s",mpassward); if(strcmp(mpassward,pwman)==0) { printf("密码正确,欢迎使用通信管理系统!\n"); system("pause"); system("cls");//清屏 while(1) { mfunctionalinterface();//经理界面函数 char mh=getch();//读取一个字符可以不按回车执行 switch (mh) { case '1': while(1) { system("cls"); mfunctionalinterface1();//经理基本信息管理界面 char mh1=getch(); switch(mh1) { case '1': end_salesman = creat_note_salesman(end_salesman); break; case '2': end_customer = creat_note_customer(end_customer); break; case '3': end_cliaison = creat_note_cliaison(end_cliaison); break; case '4': search_salesman(head_salesman); break; case '5': search_customer(head_customer); break; case '6': search_cliaison(head_cliaison); break; case '7': head_salesman = delete_salesman(head_salesman); break; case '8': head_customer = delete_customer(head_customer); break; case '9': head_cliaison = delete_cliaison(head_cliaison); break; case '0':break; default: { printf("您的输入有误,请重新输入!\n"); system("pause"); system("cls"); } } if(mh1=='0') { system("cls"); break; } } break; case '2': while(1) { system("cls"); mfunctionalinterface2();//经理客户分配界面 char mh2=getch(); switch(mh2) { case '1': allocation(head_customer,head_salesman); break;
2303_806435pww/tongxin
main.c
C
unknown
5,262
#ifndef COMMANSYSTEM_H_INCLUDED #define COMMANSYSTEM_H_INCLUDED #endif // COMMANSYSTEM_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include<conio.h> #include<string.h> #include<malloc.h> //客户联络员 struct cliaison { int clcount;//联络员编号 char clname[12];//客户联络员姓名 char clsex[3];//客户联络员性别 char clbirthday[12];//客户联络员生日 char clmailbox[15];//客户联络员邮箱 int cltelcount;//电话号码数量 char cltel[10][13];//客户联络员电话号码(定义一个二维数组考虑到一个客户联络员的电话有多个) }; struct cliaison saleclient[20];//定义一个结构数组用来表示客户联络员所负责的客户 //节点2 struct Node2 { struct cliaison cli;//联络员 struct Node2 *pnext2;//指向下一节点的指针 }; //客户 struct client { int clicount;//客户编号 char cliname[12];//客户姓名 char cliarea[10];//客户所在区域 char cliaddress[30];//客户所在地址 char clilegalman[12];//客户法人 char cliscale[3];//客户规模 char cliconlevel[3];//客户联系程度 char climailbox[15];//客户邮箱 int clitelcount;//电话号码数量 char clitel[10][13];//客户电话号码(定义一个二维数组考虑到一个客户的电话有多个) int cliordernumber;//排序数靠他来进行单一规模排序 }; //节点1 struct Node1 { struct client cli;//客户 struct Node1* pnext1;//指向下一节点的指针 struct Node2* headcliaison[20];//联络员的头指针 int cliaison_size;//客户联络员的数量 }; //业务员 struct salesman { int scount;//业务员编号 char sname[12];//业务员姓名 char ssex[3];//业务员性别 char sbirthday[12];//业务员生日 char smailbocx[15];//业务员邮箱 int stelcount;//电话号码数量 char stel[10][13];//业务员电话号码 struct Node1* saleclient[20];//定义一个结构数组用来表示业务员所负责的客户 int saleclient_size; //负责的客户数量 }; //节点3 struct Node3 { struct salesman sal;//业务员 struct Node3* pnext3;//指向下一节点的指针 }; //通信内容 struct comcontent { char ccompny[12];//客户公司名称 char cclname[12];//客户联络员名称 int year; int month; int day; int hour; int duration;//持续时间 char contnt[100];//通信内容文字记录 char comtype[20];//表示按什么类型排序和统计 int comcount;//统计数据 struct comcontent *next;//指向下一通信内容 }; //客户分组 struct cusgroup { char cusname[12];//分组名称 int size_;//表示客户数量 int _count;//分组编号 struct Node1* people[50];//组内成员 }; struct Node4 { struct cusgroup crgroup; struct Node4* pnext4;//客户分组链表指向下一个节点的指针 };
2303_806435pww/tongxin
tool.h
C
unknown
2,924
.comments-container { max-width: 100%; margin:auto; }
2303_806435pww/hexo-theme-wang
source/css/_partial/comments.styl
Stylus
unlicense
70
.footer-center{ display: flex; flex-direction: column; /* 子元素垂直排列 */ justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ border: 1px solid #ccc; } .footer{ margin-top: auto; bottom: 0; } .footer-links-container{ display: flex; flex-wrap: wrap; justify-content: center; } .footer-links-item{ width: auto; max-width: 7%; }
2303_806435pww/hexo-theme-wang
source/css/_partial/footer.styl
Stylus
unlicense
405
#header { position: fixed; width: 100%; /* 宽度100% */ z-index: 9999; /* 确保在顶部 */ transition: transform 0.5s ease-in-out, opacity 0.5s ease-in-out; /* 平滑过渡 */ transform: translateY(0); /* 初始位置 */ margin-bottom: 50px } #header.hidden-header { transform: translateY(-100%); /* 向上移动,完全移出视口 */ opacity: 0; /* 隐藏元素 */ } .header-toggle-all{ width : 100%; height: 60pX; display: grid; grid-template-columns: 1fr 4fr; background-color: #33333375; margin:0px; } .header-toggle { margin-left:10px; display: flex; align-content: center; flex : 1 1; align-items: center; } .logo{ text-decoration: none; } .logo-img { margin-right: 10px; } .logo-title { position: relative; top: 0px; left: 2px; color: white; margin:0; margin-left: 10px; } .header-subtitle{ text-align: center; word-break: break-all; justify-content: center; align-items: center; margin:auto; } .navbar { display: flex; flex:1; justify-content: right; align-items: right; //padding: 5px 0; } .menu { list-style: none; padding: 5px 0; display: flex; width: 100%; justify-content: space-between; } .menu-item { width : 100%; align-items: center; text-align: center; justify-content: center; background-color: #33333350; color: white; transition: background-color 0.3s ease, box-shadow 0.3s ease; padding: 5px; } .menu-item:hover { background-color: #444; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); } .menu-item-link { width 100%; height: 100%; display: grid; text-decoration: none; color: white; transition: background-color 0.3s; //margin-left: 8px; } .menu-column{ display: none; } #mobie-header{ display none; } #mobie-navbar{ display: none; } @media (max-width: 767px) { #mobie-header { position: fixed; display block; width: 85%; /* 宽度100% */ z-index: 9999; /* 确保在顶部 */ transition: transform 0.5s ease-in-out, opacity 0.5s ease-in-out; /* 平滑过渡 */ transform: translateY(0); /* 初始位置 */ margin-bottom: 50px } #mobie-header.hidden-header { transform: translateY(-100%); /* 向上移动,完全移出视口 */ opacity: 0; /* 隐藏元素 */ } #header{ display: none; } .mobie-header-nameicon{ display: flex; justify-content: flex-start; } .ilist{ position :fixed; top: 0; right:50%; z-index: 99999; z-index : 9999; } #mobie-navbar>.menu{ max-width: 100%; display: flex; flex-direction: column; background-color: #333333; } }
2303_806435pww/hexo-theme-wang
source/css/_partial/header.styl
Stylus
unlicense
2,820
.page-nav { margin: 10px auto; padding: 5px; max-width: 800px; width :600px; display: flex; /* 使用Flexbox布局 */ justify-content: space-between; /* 子元素均匀分布 */ align-items: center; /* 垂直居中 */ background-color: #414141fd; /* 盒子背景颜色 */ //border: 1px solid #ccc; /* 盒子边框 */ border-radius: 15px; /* 圆角效果 */ transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out; /* 平滑过渡效果 */ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 初始阴影 */ } // .page-nav:hover { // transform: translateY(-2px); /* 鼠标悬停时向上移动 */ // box-shadow: 0 12px 20px rgba(0, 0, 0, 0.2); /* 鼠标悬停时增加阴影 */ // } .pagination-prev, .pagination-next,.pagination-page { width :50px; text-align: center; /* 居中 */ display:inline-block; /* 使得元素成为块级元素 */ background-color: #414141fd; /* 盒子背景颜色 */ border: 1px solid #ccc; /* 盒子边框 */ border-radius: 5px; /* 圆角效果 */ transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out; /* 平滑过渡效果 */ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 初始阴影 */ padding: 5px; } .pagination-prev:hover,.pagination-next:hover ,.pagination-page:hover{ transform: translateY(-2px); /* 鼠标悬停时向上移动 */ box-shadow: 0 12px 20px rgba(0, 0, 0, 0.2); /* 鼠标悬停时增加阴影 */ } .pagination-current { background-color: #414141fd; /* 盒子背景颜色 */ border: 0; border-radius: 5px; /* 圆角效果 */ transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out; /* 平滑过渡效果 */ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 初始阴影 */ /* 为当前页链接添加样式 */ padding: 5px; } .pagination-space { background-color: #414141fd; /* 盒子背景颜色 */ //border: 1px solid #ccc; /* 盒子边框 */ border-radius: 5px; /* 圆角效果 */ transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out; /* 平滑过渡效果 */ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 初始阴影 */ padding: 5px; }
2303_806435pww/hexo-theme-wang
source/css/_partial/pagination.styl
Stylus
unlicense
2,169
.search-container { display: none; /* 默认隐藏搜索框 */ position: fixed; /* 使用绝对定位脱离文档流 */ top: 20%; /* 定位到窗口的垂直中心 */ left: 25%; //transform: translate(-50%, -80%); /* 使用 transform 属性微调,使其精确居中 */ width: 50%; /* 搜索框的宽度 */ max-height: 50%; z-index: 1000; /* 确保搜索框在最上层 */ } #local-search-result{ max-height: 400px; overflow: auto; /* 允许滚动条 */ display: flex; flex-direction: column; } #local-search-result li { background-color:rgb(65, 65, 65); border: 1px solid #ccc; } .search-keyword{ color: red; } /* 表单样式 */ .search-container form { display: flex; align-items: center; /* 使按钮和输入框垂直居中 */ background-color: #303030 } /* 搜索输入框样式 */ #local-search-input { flex-grow: 1; /* 输入框占据剩余空间 */ padding: 10px; /* 输入框内边距 */ border: 1px solid #ccc; /* 输入框边框颜色 */ background: #757575; /* 输入框背景颜色 */ border-radius: 4px 0 0 4px; /* 输入框圆角,左边圆角 */ outline: none; /* 移除焦点时的轮廓 */ margin:auto; color:rgb(71, 71, 71); } /* 搜索按钮样式 */ button.fa.fa-search { border: 1px solid #ccc; /* 按钮边框颜色 */ background: #797979; /* 按钮背景颜色 */ border-radius: 4px 0 0 4px; /* 按钮圆角,右边圆角 */ font-size: 1rem; /* 图标大小 */ color: rgb(231, 231, 231)ff; /* 图标颜色 */ cursor: pointer; /* 鼠标悬停时显示指针 */ padding: 10px; /* 按钮内边距 */ } button.fa.fa-xmark { border: 1px solid #ccc; /* 按钮边框颜色 */ background: #797979; /* 按钮背景颜色 */ border-radius: 0 4px 4px 0; /* 按钮圆角,右边圆角 */ font-size: 1rem; /* 图标大小 */ color: rgb(231, 231, 231)ff; /* 图标颜色 */ cursor: pointer; /* 鼠标悬停时显示指针 */ padding: 10px; /* 按钮内边距 */ }
2303_806435pww/hexo-theme-wang
source/css/_partial/search.styl
Stylus
unlicense
2,026
.sidebar-left,.sidebar-right{ //display: ; position: sticky; top: 60px; bottom: 0; margin-top: 60px; padding: 20px; width :15%; max-width: 20%; height:60%; max-height: 50%; background-color: #33333367; } @media (max-width: 767px) { .sidebar-left,.sidebar-right{ display: none; width :0; } } .title-center,.sidebar-author,.sidebar-description{ text-align: center; word-break: break-all; } .avatar{ max-width:50%; border-radius: 100%; object-fit: cover } /* 定义旋转一圈的动画 */ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } /* 定义反向旋转一圈的动画 */ @keyframes reverse-spin { from { transform: rotate(-360deg); } to { transform: rotate(0deg); } } .rounded-img:hover { animation: spin 0.5s linear forwards; } /* 鼠标离开时触发反向旋转动画 */ .rounded-img { animation: reverse-spin 0.5s linear reverse forwards; } .social-links { border: 1px solid #ddd; /* 边框 */ border-radius: 5px; /* 圆角 */ list-style-type: none; /* 去除列表项前面的点 */ padding: 0; /* 移除列表项左侧的默认内边距 */ display: flex; /* 使用 Flexbox 布局 */ flex-wrap: wrap; /* 允许子元素换行 */ justify-content: space-between; /* 水平方向上两端对齐 */ } .social-links-item { margin-bottom: 10px; /* 子元素之间的垂直间距 */ width: calc(50% - 5px); /* 每个子元素占一半的宽度,减去间距 */ } .social-links-item:nth-child(odd) { text-align: left; /* 奇数位置的子元素左对齐 */ } .social-links-item:nth-child(even) { text-align: left; } .sidebar-menu{ display: flex; flex-direction: row; margin-top: 20px; list-style-type: none justify-content: space-between; padding: 0; } .sidebar-menu-item{ display: flex; flex-direction: column; text-align: center; } .big{ font-size: 30px; } //right /* 基本样式 */ .sidebar-right { font-family: Arial, sans-serif; width: 300px; padding: 20px; //background-color: #f9f9f9; //border: 1px solid #ddd; } .sidebar-item h2 { font-size: 1.5em; margin-bottom: 10px; } /* 年份样式 */ .year-reverse { font-size: 1.2em; font-weight: bold; cursor: pointer; transition: all 0.3s ease; } /* 月份样式 */ .month-reverse { font-size: 1.1em; font-weight: 600; cursor: pointer; margin-left: 10px; transition: all 0.3s ease; } /* 日期样式 */ .day-reverse { font-size: 1em; font-weight: 500; cursor: pointer; margin-left: 20px; transition: all 0.3s ease; } /* 文章列表样式 */ ul { list-style-type: none; padding-left: 30px; } ul li { margin-bottom: 5px; } ul li a { text-decoration: none; color: #007bff; } ul li a:hover { //text-decoration: underline; } /* 动画效果 */ details summary { outline: none; } details > summary::-webkit-details-marker { display: none; } details > summary::before { content: '> '; font-size: 1em; color: #007bff; margin-right: 5px; } details[open] > summary::before { content: 'v '; } details > summary { display: flex; align-items: center; padding: 5px 0; transition: background-color 0.3s ease; } details details { margin-left: 10px; transition: max-height 0.3s ease; overflow: hidden; } details[open] details { max-height: 1000px; /* 足够大的值以显示所有内容 */ } details:not([open]) details { max-height: 0; } .ipshow{ text-align:center; } .timeshow{ text-align:center; font-size: 20px; } .timetitle{ text-align:center; } .toc-child,.toc-item{ margin-left:15px; margin-top:10px; margin-bottom:10px; } .thispost-tag,.thispost-category{ margin:2px; }
2303_806435pww/hexo-theme-wang
source/css/_partial/sidebar.styl
Stylus
unlicense
4,034
pre code.hljs { display: inline-block; max-width: 100%; padding: 1em; } code.hljs { padding: 3px 5px; } /*! Theme: a11y-dark Author: @ericwbailey Maintainer: @ericwbailey Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css */ .hljs { background: #2b2b2b; color: #f8f8f2 } /* Comment */ .comment, .quote { color: #d4d0ab } /* Red */ .variable, .template-variable, .tag, .name, .selector-id, .selector-class, .regexp, .deletion { color: #ffa07a } /* Orange */ .number, .built_in, .literal, .type, .params, .meta, .link { color: #f5ab35 } /* Yellow */ .attribute { color: #ffd700 } /* Green */ .string, .symbol, .bullet, .addition { color: #abe338 } /* Blue */ .title, .section { color: #00e0e0 } /* Purple */ .keyword, .selector-tag { color: #dcc6e0 } .emphasis { font-style: italic } .strong { font-weight: bold } @media screen and (-ms-high-contrast: active) { .addition, .attribute, .built_in, .bullet, .comment, .link, .literal, .meta, .number, .params, .string, .symbol, .type, .quote { color: highlight } .keyword, .selector-tag { font-weight: bold } }
2303_806435pww/hexo-theme-wang
source/css/a11y-dark.styl
Stylus
unlicense
1,271
.archive-container{ display:flex; justify-content: center; margin-top: 65px; margin-left: 3%; margin-right: 3%; width: 50% } //width : 50%; // .timeline{ // content: ""; // margin-top: 20px; // margin-bottom: 5%; // width:1%; // border-left: 10px dashed #ddd; // height: 97%; // //background-color: white; // } // .archive-posts-container{ // margin-top: 10px; // margin-bottom: 5%; // } // .archive-year,.archive-month,.archive-day{ // margin-bottom: 10px; // left : 5%; // } .archive-year-container{ text-align: center; //font-size: 45px; } .archive-year-month-day-container{ display: flex; flex-direction: column; text-align: center; width: 100%; padding:0; } .ahead-archive-year-container>ul,.ahead-archive-day-container>ul,.archive-container>ul{ list-style: none; padding: 10px; border: 1px solid #ddd; } .ahead-archive-month-container>ul,{ list-style: none; padding: 2px; border: 1px solid #ddd; } .ahead-archive-year-container>ul{ width :97%; } .ahead-archive-year-container{ display: block; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ width :100%; } .archive-year-container{ display: flex; flex: 1; flex-direction: column; text-align: center; width :90%; } .archive-year-container>div{ text-align: center; } .archive-month-container{ display: flex; flex-direction: row; width : 100%; flex-wrap: wrap; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ } .archive-month-container>li{ width: 20%; /* 或者指定一个固定宽度 */ height: 20%; text-align: center; } .archive-day-container{ display: flex; flex: 1; flex-direction: column; flex-direction: ; } .archive-day-container>li{ padding: 2px; border: 1px groove #ddd; } // display:flex; // margin: 5px; // border: 1px solid #ddd; // border-radius: 15px; // } // .archive-day-container-day{ // display:flex; // } // .archive-month{ // font-size: 35px;} // .archive-day{ // font-size: 25px; // } // .archive-day-container{ // border: 1px dashed #ddd; // border-radius: 15px; // padding: 15px; // } // .archive-title{ // margin-top: 20px; // text-align: center; // overflow-wrap: break-word; // font-size: 25px; // }
2303_806435pww/hexo-theme-wang
source/css/archive.styl
Stylus
unlicense
2,418
.category-cloud{ width: 100%; display: flex; flex-direction: column; flex-wrap: wrap; margin-top:60px; background-color: #33333367; text-align: center; } .categorypost{ text-align: center; width: auto; margin: 10px; padding: 10px; border-radius: 5px; border: 1px solid #D3D3D3; } .category-list-list{ width : 100%; display: flex; flex-wrap: wrap; flex:1; } .category-list-list-item{ display: flex; align-items: center; justify-content: center; margin: 5px; padding: 5px; border-radius: 5px; border: 1px solid #D3D3D3; font-size: 14px; font-weight: bold; } .category-list-list-child{ display: flex; align-items: center; justify-content: center; margin: 5px; padding: 5px; // border-radius: 5px; // border: 1px solid #D3D3D3; // font-size: 14px; // font-weight: bold; } .category-list-list-count{ padding: 5px; } .category-list-list-link{ position: relative; cursor: pointer; text-decoration: none; /* 去除默认的下划线 */ display: inline-block; padding-bottom: 2px; /* 为下划线留出空间 */ transition: all 0.3s ease-in-out; /* 过渡效果 */ } .category-list-list-link::after { content: ''; position: absolute; left: 50%; right: 50%; bottom: 0; height: 1px; /* 下划线高度 */ background: #D3D3D3; /* 灰白色 */ transition: all 0.3s ease-in-out; /* 过渡效果 */ } .category-list-list-link:hover::after { left: 0; right: 0; } .rcategory-li{ display: flex; flex-wrap: wrap; } .categories-li{ margin:auto; padding: 10px; border-radius: 5px; border: 1px solid #D3D3D3; }
2303_806435pww/hexo-theme-wang
source/css/category.styl
Stylus
unlicense
1,747
.tabs-container{ display:flex; justify-content: space-around; margin:15px; } .tablinks{ display: inline-block; width: 49vh; height: 5vh; border-radius: 0; } .unactive{ display: none; } .links-box{ display:flex; flex-wrap:wrap; justify-content: space-around; } .link-content{ display:flex; width:30%; border-radius: 5px; margin-bottom:10px; background-color: #33333367; } .link-box{ display:flex; width:100%; height:100%; } .link-img{ width:50px; height:50px; min-width : 50px; min-height : 50px; border-radius: 5px; } .link-text { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .link-title{ margin-left:10px; margin-bottom:5px; } .link-description{ font-size:14px; margin-left:10px; } .text-link{ margin:5px; }
2303_806435pww/hexo-theme-wang
source/css/links.styl
Stylus
unlicense
845