code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | 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_2931 | tls/record/src/record.h | C | unknown | 4,034 |
// @ts-check
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import sitemap from '@astrojs/sitemap';
import browserslist from 'browserslist';
import vue from '@astrojs/vue';
import astroExpressiveCode from 'astro-expressive-code';
import { remarkModifiedTime } from './src/integrations/remark-modified-time.mjs';
import { remarkModifiedAbbrlink } from './src/integrations/remark-modified-abbrlink.mjs';
import remarkToc from 'remark-toc';
import { browserslistToTargets } from 'lightningcss';
import { config_site } from './src/utils/config-adapter';
import pagefind from "astro-pagefind";
// 数学公式渲染相关插件
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import timestampIntegration from './src/integrations/timestamp-integration.mjs';
// https://astro.build/config
export default defineConfig({
build: {
format: "directory",
}, site: config_site.url,
integrations: [
timestampIntegration(),
pagefind(),
sitemap({
filter: (page) => {
// 包含所有重要页面及其子页面
return page.includes('/posts/') ||
page.includes('/about/') ||
page.includes('/links/') ||
page === config_site.url + '/' ||
page === config_site.url + '/archives/' ||
page === config_site.url + '/tags/' ||
page === config_site.url + '/categories/' ||
page.includes('/tags/') || // 所有标签页面
page.includes('/categories/'); // 所有分类页面
},
changefreq: 'weekly',
priority: 0.5,
lastmod: new Date()
}),
vue(),
astroExpressiveCode({
// You can set configuration options here
themes: ['dark-plus', 'github-light'],
styleOverrides: {
// You can also override styles
borderRadius: '0.5rem',
frames: {
shadowColor: '#124',
},
},
}),], vite: {
css: {
transformer: "lightningcss",
lightningcss: {
targets: browserslistToTargets(browserslist('>= 0.25%'))
}
}, // 处理可能不存在的_config.ts文件
plugins: [
{
name: 'handle-optional-imports',
resolveId(id, importer) {
// 捕获对 _config.ts 的导入
if (id.includes('/_config') || id.endsWith('_config')) {
try {
// 检查文件是否实际存在
const fs = require('fs');
const path = require('path');
const configPath = path.resolve('./src/_config.ts');
if (fs.existsSync(configPath)) {
// 如果存在,让 Vite 正常处理
return null;
}
// 如果文件不存在,返回虚拟模块路径
return '\0virtual:_config';
} catch (e) {
// 如果出错,返回虚拟模块
return '\0virtual:_config';
}
}
return null;
},
load(id) {
// 为虚拟模块提供默认导出
if (id === '\0virtual:_config') {
return 'export const useConfig = false; export const siteConfig = {};';
}
return null;
}
}
],
build: {
cssMinify: 'lightningcss', // 让 Vite/Rollup 静默处理一些导入错误
rollupOptions: {
onwarn(warning, warn) {
// 忽略关于找不到_config模块的警告
if (
warning.code === 'UNRESOLVED_IMPORT' &&
warning.message && warning.message.includes('_config')
) {
return;
}
// 传递其他警告
warn(warning);
}
}
}
},
// 禁用开发工具栏
devToolbar: {
enabled: false,
}, markdown: {
remarkPlugins: [remarkModifiedTime, remarkModifiedAbbrlink, [remarkToc, { heading: "contents" }], remarkMath],
rehypePlugins: [rehypeKatex],
},
}); | 2303_806435pww/stalux_moved | astro.config.mjs | JavaScript | mit | 4,090 |
import { defineEcConfig } from 'astro-expressive-code'
import { pluginLineNumbers } from '@expressive-code/plugin-line-numbers'
export default defineEcConfig({
plugins: [pluginLineNumbers()],
}) | 2303_806435pww/stalux_moved | ec.config.mjs | JavaScript | mit | 197 |
import { defineIntegration } from 'astro';
export default defineIntegration({
name: 'astro-theme-stalux',
hooks: {
'astro:config:setup': ({ updateConfig }) => {
// 这里可以添加自动配置主题所需的内容
console.log('🌟 Stalux 主题已激活,感谢您的使用!');
},
},
});
| 2303_806435pww/stalux_moved | integration.js | JavaScript | mit | 321 |
---
import type { BadgeOptions } from '../types';
import { generateBadge, svgToDataUrl } from '../utils/badge-generator';
import { config_site } from '../utils/config-adapter'
// --- 配置读取 ---
// 获取页脚配置,优先使用footer对象中的配置,兼容旧版配置
const footerConfig = config_site.footer || {};
// 作者信息
const author = config_site.author || 'Stalux';
// 版权配置
const copyrightConfig = footerConfig.copyright || config_site.footer?.copyright || { enabled: true };
// 主题信息配置
const showPoweredBy = footerConfig.theme?.showPoweredBy !== undefined
? footerConfig.theme.showPoweredBy
: config_site.footer?.theme?.showPoweredBy !== false;
const showThemeInfo = footerConfig.theme?.showThemeInfo !== undefined
? footerConfig.theme.showThemeInfo
: config_site.footer?.theme?.showThemeInfo !== false;
// 备案信息配置
const enableIcpBeian = footerConfig.beian?.icp?.enabled !== undefined
? footerConfig.beian.icp.enabled
: config_site.footer?.beian?.icp?.enabled !== false;
const icpBeian = footerConfig.beian?.icp?.number || config_site.footer?.beian?.icp?.number || '';
const enablePublicSecurityBeian = footerConfig.beian?.security?.enabled !== undefined
? footerConfig.beian.security.enabled
: config_site.footer?.beian?.security?.enabled !== false;
const publicSecurityBeian = footerConfig.beian?.security?.text || config_site.footer?.beian?.security?.text || '';
const publicSecurityBeianNumber = footerConfig.beian?.security?.number || config_site.footer?.beian?.security?.number || '';
// 徽章配置
const customBadgeOptions = footerConfig.badges || config_site.footer?.badges || [];
// 是否显示版权
const showCopyright = copyrightConfig.enabled !== false;
// 计算版权年份
const currentYear = new Date().getFullYear();
const startYear = copyrightConfig.startYear;
const copyrightYear = (startYear && startYear < currentYear) ? `${startYear}-${currentYear}` : currentYear;
// 版权自定义文本
const copyrightText = copyrightConfig.customText || '';
// 是否显示备案信息
const showBeian = (enableIcpBeian && !!icpBeian) ||
(enablePublicSecurityBeian && !!publicSecurityBeian && !!publicSecurityBeianNumber);
// 是否显示主题信息部分
const showThemeInfoSection = showPoweredBy || showThemeInfo;
// 生成所有本地徽章
const allBadges = customBadgeOptions.map((options: BadgeOptions) => ({
src: svgToDataUrl(generateBadge(options)),
alt: options.alt || `${options.label}: ${options.message}`,
href: options.href
}));
// 检查是否启用了站点运行时间
const showBuildTime = config_site.footer?.buildtime ? true : false
---
<footer class="site-footer">
<div class="footer-content">
<!-- 版权信息 -->
{showCopyright && (
<div class="copyright">
<span>© {copyrightYear} {author}.</span>
{copyrightText ? <span>{copyrightText}</span> : <span> 保留权利.</span>}
</div>
)}
<!-- 徽章展示区 -->
{allBadges.length > 0 && (
<div class="badges">
{allBadges.map((badge: { href: string | URL | null | undefined; src: string | null | undefined; alt: string | null | undefined; }) => (
badge.href ?
<a href={badge.href} target="_blank" rel="noopener noreferrer">
<img src={badge.src} alt={badge.alt} class="badge" />
</a> :
<img src={badge.src} alt={badge.alt} class="badge" />
))}
</div>
)}
<!-- 备案信息区 -->
{showBeian && (
<div class="beian-info">
{enableIcpBeian && icpBeian && (
<a
href="https://beian.miit.gov.cn/"
target="_blank"
rel="noopener noreferrer"
>
{icpBeian}
</a>
)}
{enablePublicSecurityBeian && publicSecurityBeian && publicSecurityBeianNumber && (
<a
href={`http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=${publicSecurityBeianNumber}`}
target="_blank"
rel="noopener noreferrer"
class="public-security-beian"
>
<img src="https://beian.mps.gov.cn/img/logo01.dd7ff50e.png" alt="公安备案图标" />
{publicSecurityBeian}
</a>
)}
</div>
)}
<!-- 主题信息 -->
{showThemeInfoSection && (
<div class="theme-info">
{showPoweredBy && (
<span>
Powered by
<a href="https://astro.build" target="_blank" rel="noopener noreferrer">Astro</a>
</span>
)}
{showPoweredBy && showThemeInfo && <span> | </span>}
{showThemeInfo && (
<span>
Theme is
<a href="https://github.com/xingwangzhe/stalux" target="_blank" rel="noopener noreferrer">Stalux</a>
</span>
)}
</div>
)} <!-- 站点统计信息 -->
<div class="site-stats">
<span id="vercount_container_site_uv">
本站访客数:<span id="vercount_value_site_uv">Loading...</span> 人次
</span>
<span class="stats-separator">|</span>
<span id="vercount_container_site_pv">
本站总访问量:<span id="vercount_value_site_pv">Loading...</span> 次
</span>
</div>
<!-- 站点运行时间 -->
{showBuildTime && (
<div class="site-build-time">
<span>本站已正常运行<span id="runtime-counter"></span></span>
</div>
)}
</div>
</footer>
<script define:vars={{ buildtime: config_site.footer?.buildtime }}>
if (buildtime) {
const runtimeCounter = document.getElementById('runtime-counter');
if (runtimeCounter) {
// 解析构建时间,处理多种格式
let buildTimeDate;
try {
if (typeof buildtime === 'string') {
// 日期字符串处理
const dateStr = buildtime.trim();
// 标准ISO格式: '2023-06-20T10:00:00' 或带时区的 '2023-06-20T10:00:00+08:00'
if (dateStr.includes('T')) {
// 确保正确解析带时区的ISO时间
buildTimeDate = new Date(dateStr);
// 记录解析后的时间,便于调试
console.log(`解析时间戳: ${dateStr} => ${buildTimeDate.toISOString()}`);
}
// 处理常见的中文日期格式: '2023-06-20 10:00:00'
else if (dateStr.includes(' ') && dateStr.includes(':')) {
// 分离日期和时间部分
const [datePart, timePart] = dateStr.split(' ');
if (datePart && timePart) {
const [year, month, day] = datePart.split('-');
const timeParts = timePart.split(':');
const hour = timeParts[0] || '00';
const minute = timeParts[1] || '00';
const second = timeParts[2] || '00';
// 使用 Date 构造函数 - 注意月份从0开始
buildTimeDate = new Date(
parseInt(year),
parseInt(month) - 1,
parseInt(day),
parseInt(hour),
parseInt(minute),
parseInt(second)
);
}
}
// 仅有日期的格式: '2023-06-20'
else if (dateStr.includes('-')) {
const [year, month, day] = dateStr.split('-');
// 使用 Date 构造函数 - 注意月份从0开始
buildTimeDate = new Date(
parseInt(year),
parseInt(month) - 1,
parseInt(day)
);
}
// 时间戳格式 (数字字符串)
else if (/^\d+$/.test(dateStr)) {
buildTimeDate = new Date(parseInt(dateStr));
}
// 尝试直接解析
else {
buildTimeDate = new Date(dateStr);
}
} // Date 对象
else if (buildtime instanceof Date) {
buildTimeDate = buildtime;
}
// 数字时间戳
else if (typeof buildtime === 'number') {
buildTimeDate = new Date(buildtime);
}
// 确保构建时间是有效的日期且不是未来日期
if (!buildTimeDate || isNaN(buildTimeDate.getTime())) {
console.warn('网站构建时间格式无效,无法解析: ' + buildtime);
// 使用备用日期(当前日期减去1天,作为默认值)
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
buildTimeDate = yesterday;
} else {
// 防止使用未来日期,未来日期会导致计算出负值
const now = new Date();
if (buildTimeDate.getTime() > now.getTime()) {
console.warn('构建时间设置为未来,将使用当前时间: ' + buildtime);
buildTimeDate = new Date(now.getTime() - 86400000); // 使用一天前的时间
}
}
} catch (e) {
console.error('解析网站构建时间时发生错误:', e);
// 使用备用日期(当前日期减去1天,作为默认值)
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
buildTimeDate = yesterday;
}
function updateRuntime() {
const now = new Date();
const diff = now.getTime() - buildTimeDate.getTime();
// 计算天、时、分、秒
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
// 添加千分位分隔符并格式化显示
const formatNumber = (num) => {
if (num < 1000) return String(num);
return num.toLocaleString('zh-CN');
};
// 格式化显示,添加带有特殊样式的文本
runtimeCounter.innerHTML = `${formatNumber(days)}<span class="time-unit">天</span>${hours}<span class="time-unit">时</span>${minutes}<span class="time-unit">分</span>${seconds}<span class="time-unit">秒</span>`;
}
// 初次运行
updateRuntime();
// 设置定时器,每秒更新一次
setInterval(updateRuntime, 1000);
}
}
</script>
<!-- Vercount统计脚本 -->
<script defer src="https://events.vercount.one/js"></script>
<style>
.site-footer {
width: 100%;
padding: 1.5rem 0;
text-align: center;
margin-top: auto;
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.7);
background-color: rgba(0, 0, 0, 0.1);
backdrop-filter: blur(10px);
}
.footer-content {
display: flex;
flex-direction: column;
gap: 0.8rem;
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}
.copyright {
font-weight: 500;
}
.copyright span {
margin-right: 0.3em; /* 给版权信息各部分之间增加一点间距 */
}
.badges {
display: flex;
justify-content: center;
align-items: center; /* 垂直居中对齐徽章 */
flex-wrap: wrap;
gap: 0.5rem;
}
.badge {
height: 20px;
vertical-align: middle; /* 确保图片基线对齐 */
}
.beian-info {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 1rem;
}
.beian-info a {
color: rgba(255, 255, 255, 0.7);
text-decoration: none;
transition: color 0.3s ease;
}
.beian-info a:hover {
color: rgba(255, 255, 255, 0.9);
text-decoration: underline;
}
.public-security-beian {
display: inline-flex; /* 改为 inline-flex 使其能与其他备案号在同一行 */
align-items: center;
gap: 5px;
}
.public-security-beian img {
width: 15px;
height: 15px;
display: inline-block; /* 确保图片能正确对齐 */
}
.theme-info {
font-size: 0.85rem;
}
.theme-info a {
color: rgba(255, 255, 255, 0.8);
text-decoration: none;
transition: color 0.3s ease;
}
.theme-info a:hover {
color: rgba(255, 255, 255, 1);
text-decoration: underline;
}
.site-build-time {
margin-top: 0.5rem;
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.8);
}
.site-build-time .time-unit {
font-size: 0.8em;
opacity: 0.85;
margin: 0 2px;
color: rgba(255, 255, 255, 0.7);
}
.site-stats {
font-size: 0.85rem;
color: rgba(255, 255, 255, 0.8);
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
}
.stats-separator {
margin: 0 0.5rem;
opacity: 0.6;
}
#vercount_container_site_uv,
#vercount_container_site_pv {
display: inline-block;
}
#vercount_value_site_uv,
#vercount_value_site_pv {
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
}
@media (max-width: 768px) {
.site-footer {
padding: 1.2rem 0;
font-size: 0.8rem;
}
.footer-content {
gap: 0.6rem;
padding: 0 0.8rem;
}
.site-stats {
flex-direction: column;
gap: 0.3rem;
font-size: 0.8rem;
}
.stats-separator {
display: none;
}
.beian-info {
flex-direction: column;
gap: 0.5rem;
}
.badges {
gap: 0.3rem;
}
.badge {
height: 18px;
}
.theme-info {
font-size: 0.75rem;
}
}
</style>
| 2303_806435pww/stalux_moved | src/components/Footer.astro | Astro | mit | 13,177 |
---
// Head.astro - 页面头部元数据组件
// 使用 astro-seo 插件优化 SEO
import { config_site } from '../utils/config-adapter';
import { SEO, type TwitterCardType } from 'astro-seo';
import "@fancyapps/ui/dist/fancybox/fancybox.css";
// 定义组件接收的属性
interface Props {
title?: string;
author?: string;
description?: string;
favicon?: string;
url?: string;
keywords?: string;
ogImage?: string;
twitterImage?: string;
twitterCreator?: string;
lang?: string;
locale?: string;
siteName?: string;
structuredData?: string | Record<string, any>;
noindex?: boolean; // 控制页面是否被索引
head?: string; // 硬嵌入的head内容
canonical?: string; // 规范链接
openGraph?: { // 自定义 Open Graph 配置
basic: {
title: string;
type: string;
image: string;
url?: string;
},
optional?: {
audio?: string;
description?: string;
determiner?: string;
locale?: string;
localeAlternate?: string[];
siteName?: string;
video?: string;
},
image?: {
url?: string;
secureUrl?: string;
type?: string;
width?: number;
height?: number;
alt?: string;
},
article?: {
publishedTime?: string;
modifiedTime?: string;
expirationTime?: string;
authors?: string[];
section?: string;
tags?: string[];
}
};
twitter?: { // 自定义 Twitter 卡片配置
card?: TwitterCardType;
site?: string;
creator?: string;
title?: string;
description?: string;
image?: string;
imageAlt?: string;
};
extend?: { // 扩展元标签
link?: Record<string, any>[];
meta?: Record<string, any>[];
};
titleTemplate?: string; // 标题模板,如 "%s | 网站名称"
titleDefault?: string; // 默认标题,用于替换模板中的%s
}
// 从站点配置获取默认值
const siteDefaults = {
title: config_site.title,
description: config_site.description,
url: config_site.url,
author: config_site.author,
siteName: config_site.siteName,
favicon: config_site.favicon ,
lang: config_site.lang || 'zh-CN',
locale: config_site.locale || 'zh_CN',
keywords: config_site.keywords,
head: config_site.head,
}
// 接收组件属性
const {
title = siteDefaults.title,
author = siteDefaults.author,
description = siteDefaults.description,
favicon = siteDefaults.favicon,
url = siteDefaults.url,
keywords = siteDefaults.keywords,
ogImage,
twitterImage,
twitterCreator,
lang = siteDefaults.lang,
locale = siteDefaults.locale,
siteName = siteDefaults.siteName,
structuredData,
noindex = false,
head = siteDefaults.head,
canonical = url, // 规范链接默认为URL
openGraph, // 自定义 Open Graph 配置
twitter, // 自定义 Twitter 卡片配置
extend = {}, // 扩展元标签
titleTemplate, // 标题模板
titleDefault = title // 默认标题
} = Astro.props;
// 准备默认的OpenGraph配置
const defaultOgConfig = ogImage ? {
basic: {
title: title,
type: "website",
image: ogImage,
url: url,
},
optional: {
description: description,
locale: locale,
siteName: siteName,
}
} : undefined;
// 准备默认的Twitter配置
const defaultTwitterConfig = (twitterImage || ogImage) ? {
card: "summary_large_image" as TwitterCardType,
site: siteName,
creator: twitterCreator,
title: title,
description: description,
image: twitterImage || ogImage,
} : undefined;
// Import the favicon image
import favicon_img from '../images/stalux.ico';
---
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- 使用 astro-seo 插件整合所有 SEO 相关标签 -->
<SEO
title={title}
titleTemplate={titleTemplate}
titleDefault={titleDefault}
description={description}
canonical={canonical}
noindex={noindex}
nofollow={noindex}
openGraph={openGraph || defaultOgConfig}
twitter={twitter || defaultTwitterConfig}
extend={{
meta: [
{ name: "author", content: author },
...(keywords ? [{ name: "keywords", content: keywords }] : []),
{ "http-equiv": "content-language", content: lang },
...(extend.meta || []),
], link: [
{ rel: "icon", href: favicon || favicon_img , type: "image/x-icon" },
{ rel: "alternate", type: "application/rss+xml", title: `${siteName || title} RSS Feed`, href: `/rss.xml` },
{ rel: "alternate", type: "application/atom+xml", title: `${siteName || title} Atom Feed`, href: `/atom.xml` },
{ rel: "alternate", type: "application/sitemap+xml", title: `${siteName || title} Sitemap index Feed`, href: `/sitemap-index.xml` },
...(extend.link || []),
],
}}
/>
<meta name="color-scheme" content="dark">
<!-- 使用插槽允许自定义 robots meta 标签 -->
<slot name="robots"></slot>
{/* 结构化数据,如果是字符串则直接使用,否则转换为JSON字符串 */}
{structuredData && <script type="application/ld+json" set:html={
typeof structuredData === 'string' ? structuredData : JSON.stringify(structuredData)
} />}
<!-- 硬嵌入的head元素 -->
{head && <Fragment set:html={head} />}
<!-- 通用插槽,用于添加其他head元素 -->
<slot name="head" />
</head> | 2303_806435pww/stalux_moved | src/components/Head.astro | Astro | mit | 5,390 |
---
import { config_site } from '../utils/config-adapter';
// @ts-ignore
import * as feather from 'feather-icons';
import Search from './Search.astro';
// TypeScript类型定义
interface NavItem {
title: string;
path: string;
icon?: string;
}
// 获取导航配置
const navItems: NavItem[] = config_site.nav || [];
// 从feather图标库获取图标的辅助函数
function getIconSvg(iconName: string): string {
if (!iconName) return '';
try {
const icon = feather.icons[iconName];
return icon ? icon.toSvg({
width: 20,
height: 20,
'stroke-width': 2,
class: 'nav-icon'
}) : '';
} catch (error) {
console.error(`Icon '${iconName}' not found in feather-icons`);
return '';
}
}
import '../styles/components/Header.styl';
---
<nav class="nav"> <button id="mobile-menu-toggle" class="mobile-menu-toggle" aria-label="导航菜单" aria-expanded="false">
<span class="menu-icon-wrapper">
<Fragment set:html={feather.icons['menu'].toSvg({
width: 24,
height: 24,
class: 'menu-icon menu-open'
})} />
<Fragment set:html={feather.icons['x'].toSvg({
width: 24,
height: 24,
class: 'menu-icon menu-close'
})} />
</span>
</button>
<ul id="nav-menu">
{navItems.map((item) => (
<li>
<a href={item.path} class="nav-link">
{item.icon && (
<span class="nav-icon-container" set:html={getIconSvg(item.icon)} />
)}
<span>{item.title}</span>
</a>
</li> ))}
<li>
<p class="nav-link search-toggle" id="search-toggle">
<span class="nav-icon-container" set:html={feather.icons['search'].toSvg({
width: 20,
height: 20,
'stroke-width': 2,
class: 'nav-icon'
})} />
<span>搜索</span>
</p>
</li>
</ul>
</nav>
<!-- 移动端菜单遮罩层 -->
<div id="mobile-menu-backdrop" class="mobile-menu-backdrop"></div>
<div id="search-container" class="search-container">
<div class="search-backdrop"></div>
<div class="search-box">
<div class="search-header">
<h2>站内搜索</h2>
<button class="search-close" id="search-close">
<Fragment set:html={feather.icons['x'].toSvg({
width: 24,
height: 24,
class: 'close-icon'
})} />
</button>
</div>
<div class="search-content">
<Search />
</div>
</div>
</div>
<script>
// 移动端菜单交互逻辑
document.addEventListener('DOMContentLoaded', () => {
const menuToggle = document.getElementById('mobile-menu-toggle');
const navMenu = document.getElementById('nav-menu');
const searchToggle = document.getElementById('search-toggle');
const searchContainer = document.getElementById('search-container');
const searchClose = document.getElementById('search-close');
const searchBackdrop = document.querySelector('.search-backdrop'); const mobileMenuBackdrop = document.getElementById('mobile-menu-backdrop');
if (menuToggle && navMenu && mobileMenuBackdrop) {
menuToggle.addEventListener('click', () => {
if (navMenu.classList.contains('active')) {
// 关闭菜单
navMenu.classList.remove('active');
menuToggle.setAttribute('aria-expanded', 'false');
mobileMenuBackdrop.classList.remove('active');
} else {
// 打开菜单
navMenu.classList.add('active');
menuToggle.setAttribute('aria-expanded', 'true');
mobileMenuBackdrop.classList.add('active');
}
});
// 点击菜单项后关闭菜单
const menuItems = navMenu.querySelectorAll('a, .search-toggle');
menuItems.forEach(item => {
item.addEventListener('click', () => {
if (window.innerWidth <= 768) {
navMenu.classList.remove('active');
menuToggle.setAttribute('aria-expanded', 'false');
mobileMenuBackdrop.classList.remove('active');
}
});
});
// 点击遮罩层关闭菜单
if (mobileMenuBackdrop) {
mobileMenuBackdrop.addEventListener('click', () => {
navMenu.classList.remove('active');
menuToggle.setAttribute('aria-expanded', 'false');
mobileMenuBackdrop.classList.remove('active');
});
}
// 点击菜单外部关闭菜单
document.addEventListener('click', (e) => {
if (window.innerWidth <= 768 &&
!navMenu.contains(e.target as Node) &&
!menuToggle.contains(e.target as Node) &&
!mobileMenuBackdrop.contains(e.target as Node) &&
navMenu.classList.contains('active')) {
navMenu.classList.remove('active');
menuToggle.setAttribute('aria-expanded', 'false');
mobileMenuBackdrop.classList.remove('active');
}
});
// ESC键关闭菜单
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && navMenu.classList.contains('active')) {
navMenu.classList.remove('active');
menuToggle.setAttribute('aria-expanded', 'false');
mobileMenuBackdrop.classList.remove('active');
}
});
}
// 搜索框交互逻辑
if (searchToggle && searchContainer && searchClose) {
// 点击搜索按钮显示搜索框
searchToggle.addEventListener('click', () => {
searchContainer.classList.add('active');
document.body.style.overflow = 'hidden'; // 防止背景滚动
// 聚焦到搜索输入框
setTimeout(() => {
const searchInput = document.querySelector('.pagefind-ui__search-input');
if (searchInput) {
(searchInput as HTMLElement).focus();
}
}, 100);
});
// 点击关闭按钮隐藏搜索框
searchClose.addEventListener('click', () => {
searchContainer.classList.remove('active');
document.body.style.overflow = ''; // 恢复背景滚动
});
// 点击遮罩层关闭搜索框
if (searchBackdrop) {
searchBackdrop.addEventListener('click', () => {
searchContainer.classList.remove('active');
document.body.style.overflow = '';
});
}
// ESC键关闭搜索框
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && searchContainer.classList.contains('active')) {
searchContainer.classList.remove('active');
document.body.style.overflow = '';
}
});
}
});
</script> | 2303_806435pww/stalux_moved | src/components/Header.astro | Astro | mit | 6,445 |
---
// 移除 Posts prop,改为客户端获取
---
<div class="postlist-wrapper">
<div id="posts-container" class="posts-container" style="display: none;">
<div class="posts-grid" id="posts-grid">
<!-- 文章将通过 JavaScript 动态加载 -->
</div>
</div>
<div id="load-posts-trigger" class="load-posts-trigger">
<div class="loading-indicator">
<div class="spinner"></div>
<span>正在加载更多内容...</span>
</div>
</div>
</div>
<script>
// 从 /allpost.json API 获取文章数据
async function fetchAllPosts() {
try {
const response = await fetch('/allpost.json');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.Posts || [];
} catch (error) {
console.error('Failed to fetch posts:', error);
return [];
}
}
// 生成文章卡片HTML
function generatePostHTML(post: any) {
// 处理标签
const tagsHTML = post.tags && post.tags.length > 0 ?
`<div class="post-tags">
${post.tags.map((tag: any) => `<span class="tag">${tag}</span>`).join('')}
</div>` : '';
// 处理日期显示
const formatDate = (dateString: string) => {
if (!dateString) return '';
try {
const date = new Date(dateString);
if (isNaN(date.getTime())) return '';
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
} catch (error) {
console.warn('Invalid date format:', dateString);
return '';
}
};
const createDate = formatDate(post.date);
const updateDate = formatDate(post.updated);
// 生成日期信息HTML
let dateHTML = '';
if (createDate) {
dateHTML += `<span class="post-date create-date" title="创建时间">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
<line x1="16" y1="2" x2="16" y2="6"></line>
<line x1="8" y1="2" x2="8" y2="6"></line>
<line x1="3" y1="10" x2="21" y2="10"></line>
</svg>
${createDate}
</span>`;
}
if (updateDate && updateDate !== createDate) {
dateHTML += `<span class="post-date update-date" title="更新时间">
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2"/>
</svg>
${updateDate}
</span>`;
}
return `
<article class="post-card">
<a href="${post.link}">
<h2 class="post-title">${post.title}</h2>
<p class="post-description">${post.description || ''}</p>
<div class="post-meta">
${dateHTML ? `<div class="post-dates">${dateHTML}</div>` : ''}
${tagsHTML}
</div>
</a>
</article>
`;
}
// 渲染所有文章
function renderPosts(posts: any[]) {
const postsGrid = document.getElementById('posts-grid');
if (!postsGrid) return;
if (posts.length === 0) {
postsGrid.innerHTML = '<div class="no-posts">暂无文章</div>';
return;
}
postsGrid.innerHTML = posts.map((post: any) => generatePostHTML(post)).join('');
console.log('Generated HTML for', posts.length, 'posts');
console.log('First post HTML:', posts.length > 0 ? generatePostHTML(posts[0]) : 'No posts');
// 添加渐入动画 - 移除手动透明度控制,让CSS动画处理
const postCards = postsGrid.querySelectorAll('.post-card');
console.log('Found', postCards.length, 'post cards in DOM');
postCards.forEach((card, index) => {
const htmlCard = card as HTMLElement;
htmlCard.style.animationDelay = `${index * 0.1}s`;
console.log(`Card ${index}:`, htmlCard.className, 'computed style:', window.getComputedStyle(htmlCard).backgroundColor);
// 移除手动透明度控制,让CSS动画自然执行
});
}
document.addEventListener('DOMContentLoaded', function() {
const postsContainer = document.getElementById('posts-container');
const loadTrigger = document.getElementById('load-posts-trigger');
let postsLoaded = false;
let isLoading = false;
// 智能检测用户行为
let userInteractionDetected = false;
let scrollStartTime = 0;
let idleTimeout: ReturnType<typeof setTimeout> | undefined;
// 检测用户交互
function detectUserInteraction() {
if (!userInteractionDetected) {
userInteractionDetected = true;
// 用户开始交互后,降低加载阈值
startSmartLoading();
}
}
// 监听多种用户交互
['scroll', 'mousemove', 'keydown', 'click', 'touchstart'].forEach(event => {
window.addEventListener(event, detectUserInteraction, { once: true, passive: true });
});
// 智能加载逻辑
function startSmartLoading() {
// 使用 Intersection Observer 监听触发器
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && !postsLoaded && !isLoading) {
loadPosts();
}
});
}, {
rootMargin: '200px' // 提前200px开始加载
});
if (loadTrigger) {
observer.observe(loadTrigger);
}
// 备用滚动检测
let ticking = false;
function handleScroll() {
if (!ticking && !postsLoaded && !isLoading) {
requestAnimationFrame(() => {
const scrollPosition = window.innerHeight + window.scrollY;
const documentHeight = document.documentElement.offsetHeight;
const scrollPercent = (scrollPosition / documentHeight) * 100;
// 根据滚动速度调整加载阈值
const currentTime = Date.now();
if (scrollStartTime === 0) {
scrollStartTime = currentTime;
}
const scrollDuration = currentTime - scrollStartTime;
const fastScroll = scrollDuration < 1000; // 快速滚动
const threshold = fastScroll ? 60 : 70; // 动态阈值
if (scrollPercent >= threshold) {
loadPosts();
}
ticking = false;
});
}
ticking = true;
}
window.addEventListener('scroll', handleScroll, { passive: true });
}
// 加载文章函数
async function loadPosts() {
if (isLoading || postsLoaded || !postsContainer) return;
isLoading = true;
// 显示加载动画
if (loadTrigger) {
loadTrigger.style.display = 'flex';
}
try {
// 从 API 获取文章数据
const posts = await fetchAllPosts();
// 渲染文章
renderPosts(posts);
console.log('Posts rendered:', posts.length, 'articles');
// 显示文章容器
postsContainer.style.display = 'block';
postsContainer.classList.add('show');
postsContainer.style.animation = 'fadeInUp 0.8s ease-in-out forwards';
console.log('Posts container displayed');
postsLoaded = true;
// 预加载图片
preloadImages();
} catch (error) {
console.error('Error loading posts:', error);
const postsGrid = document.getElementById('posts-grid');
if (postsGrid) {
postsGrid.innerHTML = '<div class="error">加载文章失败,请刷新页面重试</div>';
postsContainer.style.display = 'block';
postsContainer.classList.add('show');
}
} finally {
// 隐藏加载动画
if (loadTrigger) {
loadTrigger.style.display = 'none';
}
isLoading = false;
}
}
// 预加载图片
function preloadImages() {
const images = postsContainer?.querySelectorAll('img');
images?.forEach(img => {
if (img.dataset.src) {
img.src = img.dataset.src;
}
});
}
// 空闲时自动加载
function scheduleIdleLoading() {
if (idleTimeout) {
clearTimeout(idleTimeout);
}
idleTimeout = setTimeout(() => {
if (!postsLoaded && userInteractionDetected) {
loadPosts();
}
}, 3000); // 3秒空闲后加载
}
// 监听用户空闲状态
['scroll', 'mousemove', 'keydown', 'click'].forEach(event => {
window.addEventListener(event, scheduleIdleLoading, { passive: true });
});
// 页面完全加载后的处理
window.addEventListener('load', () => {
// 页面完全加载后自动加载文章,不需要等待用户交互
setTimeout(() => {
if (!postsLoaded) {
loadPosts();
}
}, 500);
});
// 如果页面已经加载完成,立即执行
if (document.readyState === 'complete') {
setTimeout(() => {
if (!postsLoaded) {
loadPosts();
}
}, 500);
}
// 页面可见性变化时的处理
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && userInteractionDetected && !postsLoaded) {
// 页面重新可见时延迟加载
setTimeout(() => {
if (!postsLoaded) {
loadPosts();
}
}, 1000);
}
});
// 网络状态检测
if ('connection' in navigator) {
const connection = (navigator as any).connection;
if (connection && connection.effectiveType === '5g') {
// 5G网络下更积极加载
setTimeout(() => {
if (!postsLoaded && userInteractionDetected) {
loadPosts();
}
}, 1500);
}
}
// 备用自动加载:如果3秒后还没有加载,自动触发加载
setTimeout(() => {
if (!postsLoaded && !isLoading) {
console.log('Auto-loading posts after 3 seconds...');
loadPosts();
}
}, 3000);
});
</script>
<style is:global>
.postlist-wrapper {
width: 100%;
max-width: 1400px;
margin: 0 auto;
}
.posts-container {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.8s ease, transform 0.8s ease;
}
.posts-container[style*="display: block"] {
opacity: 1;
transform: translateY(0);
}
/* 确保容器在显示时能正确应用样式 */
.posts-container.show {
opacity: 1;
transform: translateY(0);
}
.load-posts-trigger {
display: none;
justify-content: center;
align-items: center;
margin: 2rem 0;
padding: 1rem;
opacity: 0.8;
}
.loading-indicator {
display: flex;
align-items: center;
gap: 1rem;
color: rgba(255, 255, 255, 0.7);
font-size: 0.9rem;
}
.spinner {
width: 20px;
height: 20px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top: 2px solid rgba(255, 255, 255, 0.8);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes fadeInUp {
0% {
opacity: 0;
transform: translateY(30px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.posts-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.5rem;
padding: 1rem;
width: 100%;
}
.postlist-wrapper .post-card {
background-color: rgba(0, 0, 0, 0.2);
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
padding: 1.5rem;
transition: transform 0.2s ease, box-shadow 0.2s ease;
cursor: pointer;
animation: fadeInUp 0.6s ease-in-out forwards;
opacity: 0;
animation-fill-mode: forwards;
display: flex !important;
flex-direction: column !important;
height: 100% !important;
}
.postlist-wrapper .post-card a {
display: flex !important;
flex-direction: column !important;
height: 100% !important;
text-decoration: none !important;
color: inherit !important;
}
.postlist-wrapper .post-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
background-color: rgba(0, 0, 0, 0.25);
}
.post-title {
margin: 0 0 0.75rem 0;
font-size: 1.25rem;
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
line-height: 1.3;
text-shadow: 0.1rem 0.1rem 0.3rem rgba(1, 162, 190, 0.3);
}
.post-description {
margin: 0 0 1rem 0;
color: rgba(255, 255, 255, 0.7);
line-height: 1.6;
font-size: 0.9rem;
}
.post-meta {
margin-top: auto;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.post-dates {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.post-date {
display: inline-flex;
align-items: center;
gap: 0.25rem;
background-color: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.75);
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 0.7rem;
font-weight: 400;
transition: all 0.2s ease;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.post-date svg {
flex-shrink: 0;
opacity: 0.8;
}
.create-date {
background-color: rgba(100, 200, 255, 0.1);
color: rgba(100, 200, 255, 0.9);
border-color: rgba(100, 200, 255, 0.2);
}
.update-date {
background-color: rgba(255, 200, 100, 0.1);
color: rgba(255, 200, 100, 0.9);
border-color: rgba(255, 200, 100, 0.2);
}
.post-date:hover {
transform: translateY(-1px);
background-color: rgba(255, 255, 255, 0.15);
border-color: rgba(255, 255, 255, 0.3);
}
.create-date:hover {
background-color: rgba(100, 200, 255, 0.2);
border-color: rgba(100, 200, 255, 0.4);
}
.update-date:hover {
background-color: rgba(255, 200, 100, 0.2);
border-color: rgba(255, 200, 100, 0.4);
}
.post-tags {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.tag {
background-color: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.9);
padding: 0.2rem 0.5rem;
border-radius: 4px;
font-size: 0.75rem;
font-weight: 500;
transition: all 0.2s ease;
}
.tag:hover {
background-color: rgba(255, 255, 255, 0.25);
transform: translateY(-2px);
}
/* 无文章和错误状态样式 */
.no-posts, .error {
text-align: center;
padding: 2rem;
color: rgba(255, 255, 255, 0.7);
font-size: 1rem;
grid-column: 1 / -1; /* 占满整个网格 */
}
.error {
color: rgba(255, 100, 100, 0.8);
}
/* 优化移动端体验 */
@media (max-width: 768px) {
.posts-grid {
grid-template-columns: 1fr;
padding: 0.5rem;
gap: 1rem;
}
.post-card {
padding: 1rem;
}
.post-title {
font-size: 1.1rem;
}
.post-dates {
gap: 0.5rem;
}
.post-date {
font-size: 0.65rem;
padding: 0.2rem 0.4rem;
}
.post-date svg {
width: 10px;
height: 10px;
}
.tag {
font-size: 0.7rem;
padding: 0.15rem 0.4rem;
}
.load-posts-trigger {
margin: 1rem 0;
padding: 0.5rem;
}
.loading-indicator {
font-size: 0.8rem;
}
.spinner {
width: 16px;
height: 16px;
}
}
@media (min-width: 769px) and (max-width: 1024px) {
.posts-grid {
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
}
}
@media (min-width: 1025px) {
.posts-grid {
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
}
}
</style> | 2303_806435pww/stalux_moved | src/components/Postlist.astro | Astro | mit | 19,032 |
---
import SearchS from "astro-pagefind/components/Search";
import '../styles/components/Search.styl';
---
<SearchS
id="search"
className="pagefind-ui"
uiOptions={{
showImages: false,
placeholderText: "",
showEmptyResults: true,
showSubResults: true,
resetStyles: true,
translations: {
placeholder: "",
clear_search: "清除",
load_more: "加载更多结果",
search_label: "搜索网站",
filters_label: "筛选",
zero_results: "未找到与 [SEARCH_TERM] 相关的结果",
many_results: "找到 [COUNT] 个与 [SEARCH_TERM] 相关的结果",
one_result: "找到 1 个与 [SEARCH_TERM] 相关的结果",
searching: "搜索 [SEARCH_TERM] 中..."
}
}}
/>
| 2303_806435pww/stalux_moved | src/components/Search.astro | Astro | mit | 749 |
---
import { getCollection } from 'astro:content';
import { extractFlatCategories, type CategoryNode } from '../../utils/category-utils';
import { processFrontmatter } from '../../integrations/process-frontmatter';
// 接收当前文章的分类参数
const { currentCategories = [] as string[] } = Astro.props;
// 如果有当前文章分类,直接显示;否则获取所有分类
let categoryList: CategoryNode[];
// 获取所有文章并处理frontmatter(无论是否有当前分类都需要统计)
const allPosts = await getCollection('posts');
const processedPosts = await Promise.all(allPosts.map(post => processFrontmatter(post)));
if (currentCategories && currentCategories.length > 0) {
// 显示当前文章的分类,但需要统计每个分类的文章数量
const allCategoryList = extractFlatCategories(processedPosts);
categoryList = currentCategories.map((cat: string) => {
// 在所有分类中找到对应的分类以获取正确的统计数量
const foundCategory = allCategoryList.find(c => c.name === cat);
return {
name: cat,
path: cat,
count: foundCategory ? foundCategory.count : 0,
posts: foundCategory ? foundCategory.posts : []
};
});
} else {
// 使用新的平铺分类函数处理所有文章的分类数据
categoryList = extractFlatCategories(processedPosts);
}
import '../../styles/components/categories/SidebarCategories.styl';
---
<!-- 文章分类部分 -->
<div class="sidebar-section categories">
<div class="section-header">
<h3>{currentCategories && currentCategories.length > 0 ? '本文分类' : '文章分类'}</h3>
<button id="categories-toggle" class="section-toggle" aria-label="折叠分类">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
<path fill="currentColor" d="M7 10l5 5 5-5z"></path>
</svg>
</button>
</div> <div id="categories-content" class="section-content">
<div class="category-list"> {categoryList && categoryList.length > 0 ? (
categoryList.map((category: CategoryNode) => (
<a href={`/categories/${category.name}/`} class="category-tag">
<span class="category-name">{category.name}</span>
<span class="category-count">({category.count})</span>
</a>
))
) : (
<div class="no-categories">暂无分类</div>
)}
</div>
</div>
</div>
<script>
// 分类折叠/展开功能
document.addEventListener('DOMContentLoaded', () => {
const toggleBtn = document.getElementById('categories-toggle');
const contentEl = document.getElementById('categories-content');
if (toggleBtn && contentEl) {
toggleBtn.addEventListener('click', () => {
const isCollapsing = !contentEl.classList.contains('collapsed');
if (isCollapsing) {
// 快速折叠 (250ms)
contentEl.style.transition = 'max-height 0.25s ease, opacity 0.25s ease';
} else {
// 缓慢展开 (600ms)
contentEl.style.transition = 'max-height 0.6s ease, opacity 0.6s ease';
}
contentEl.classList.toggle('collapsed');
toggleBtn.classList.toggle('collapsed');
});
}
});
</script> | 2303_806435pww/stalux_moved | src/components/categories/SidebarCategories.astro | Astro | mit | 3,261 |
<script setup lang="ts" vapor>
/**
* Waline评论组件 - Vue版本
* 集成Waline评论系统,风格与博客主题保持一致
*/
import { ref, onMounted, watch, onBeforeUnmount, computed } from 'vue';
import { init, type WalineInstance } from '@waline/client';
import '@waline/client/style'; // 正确导入CSS路径
// 引入类型定义,但不导入实际配置
import type { SiteConfig, WalineConfig } from '../../types';
// 定义组件参数 - 将所有必要的配置拆分为单独参数
interface Props {
path?: string;
title?: string;
serverURL?: string;
// 细分 Waline 配置项,避免传递整个配置对象
lang?: string;
emoji?: any;
requiredFields?: string[];
reaction?: boolean;
meta?: string[];
wordLimit?: number;
pageSize?: number;
}
const props = withDefaults(defineProps<Props>(), {
path: '',
title: '',
serverURL: '',
lang: 'zh-CN',
emoji: false,
requiredFields: () => [],
reaction: true,
meta: () => ['nick', 'mail', 'link'],
wordLimit: 200,
pageSize: 10
});
const commentRef = ref<HTMLElement | null>(null);
const walineInstance = ref<WalineInstance | null>(null);
// 初始化Waline评论系统
const initWaline = () => {
if (!props.serverURL || !commentRef.value) return;
// 销毁之前的实例
if (walineInstance.value) {
walineInstance.value.destroy();
}
// 创建新实例 - 直接使用从props接收的配置项
walineInstance.value = init({
el: commentRef.value,
serverURL: props.serverURL,
path: props.path || window.location.pathname,
lang: props.lang,
emoji: props.emoji,
requiredFields: props.requiredFields,
reaction: props.reaction,
meta: props.meta,
wordLimit: props.wordLimit,
pageSize: props.pageSize,
title: props.title,
dark: true // 固定使用暗色模式
});
};
// 监听路径变化,重新初始化评论
watch(() => props.path, () => {
initWaline();
});
// 组件挂载时初始化Waline
onMounted(() => {
if (props.serverURL) {
initWaline();
}
});
// 组件卸载前清理
onBeforeUnmount(() => {
if (walineInstance.value) {
walineInstance.value.destroy();
}
});
</script>
<template>
<div class="waline-comment-container" v-if="serverURL">
<h2 class="waline-comment-title">留言评论</h2>
<!-- Use data-nosnippet attribute which tells search engines not to include this content in search results snippets -->
<div ref="commentRef" class="waline-comment" data-nosnippet aria-hidden="true"></div>
<!-- Use a more targeted approach instead of robots meta tag -->
<div class="comments-seo-notice" style="display:none">评论区内容由用户生成,不代表网站观点</div>
</div>
</template>
<style>
/* 评论区容器与博客风格一致 */
.waline-comment-container {
margin-top: 3rem;
padding: 2rem;
border-radius: 12px;
background-color: rgba(0, 0, 0, 0.1);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.753);
animation: fadeInUp 0.8s ease-in-out forwards;
opacity: 0;
animation-delay: 0.3s;
}
/* 评论区标题样式与博客风格一致 */
.waline-comment-title {
margin: 0 0 1.5rem 0;
font-size: 2rem;
text-align: center;
background: linear-gradient(90deg, rgba(255, 255, 255, 0.9), rgba(1, 162, 190, 0.9));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Waline根元素自定义 */
.waline-comment .wl-panel {
background-color: rgba(17, 17, 17, 0.3);
border-radius: 12px;
padding: 1rem;
border: 1px solid rgba(255, 255, 255, 0.1);
margin-bottom: 1.5rem;
}
/* 修改输入框样式 */
.waline-comment .wl-editor,
.waline-comment .wl-input {
background-color: rgba(17, 17, 17, 0.5);
color: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(100, 100, 100, 0.3);
border-radius: 8px;
transition: all 0.3s ease;
}
/* 输入框焦点状态 */
.waline-comment .wl-editor:focus,
.waline-comment .wl-input:focus {
border-color: rgba(1, 162, 190, 0.5);
box-shadow: 0 0 5px rgba(1, 162, 190, 0.3);
outline: none;
}
/* 按钮样式统一 */
.waline-comment .wl-btn {
background: rgba(1, 162, 190, 0.8);
color: #fff;
border: none;
border-radius: 6px;
transition: all 0.2s ease;
font-weight: 500;
padding: 8px 15px;
cursor: pointer;
}
.waline-comment .wl-btn:hover {
background: rgba(1, 162, 190, 1);
transform: translateY(-2px);
box-shadow: 0 3px 8px rgba(1, 162, 190, 0.3);
}
.waline-comment .wl-btn.primary {
background: linear-gradient(135deg, rgba(1, 162, 190, 0.8), rgba(1, 130, 170, 0.8));
}
.waline-comment .wl-btn.primary:hover {
background: linear-gradient(135deg, rgba(1, 162, 190, 1), rgba(1, 130, 170, 1));
}
/* 标签文字颜色 */
.waline-comment .wl-header label {
color: rgba(255, 255, 255, 0.85);
font-weight: 500;
}
/* 评论卡片样式 */
.waline-comment .wl-card {
background-color: rgba(17, 17, 17, 0.3);
border-radius: 12px;
padding: 1.2rem;
margin-top: 1.2rem;
border: 1px solid rgba(70, 70, 70, 0.2);
transition: all 0.3s ease;
}
.waline-comment .wl-card:hover {
transform: translateY(-3px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
border-color: rgba(1, 162, 190, 0.3);
}
/* 修改用户名样式 */
.waline-comment .wl-nick {
color: rgba(1, 162, 190, 0.95);
font-weight: 600;
transition: all 0.2s ease;
}
.waline-comment .wl-nick:hover {
color: rgba(1, 162, 190, 1);
text-decoration: underline;
}
/* 评论内容样式 */
.waline-comment .wl-content {
color: rgba(255, 255, 255, 0.9);
line-height: 1.7;
margin: 0.8rem 0;
word-break: break-word;
}
/* 回复按钮样式 */
.waline-comment .wl-reply {
opacity: 0.8;
transition: all 0.2s ease;
}
.waline-comment .wl-reply:hover {
opacity: 1;
text-decoration: none;
}
/* 表情面板样式 */
.waline-comment .wl-emoji-popup,
.waline-comment .wl-gif-popup {
background-color: rgba(25, 25, 25, 0.95);
border: 1px solid rgba(70, 70, 70, 0.3);
border-radius: 10px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(10px);
}
/* 表情按钮样式 */
.waline-comment .wl-emoji-popup button {
border-radius: 6px;
transition: all 0.2s ease;
}
.waline-comment .wl-emoji-popup button:hover {
background-color: rgba(1, 162, 190, 0.2);
transform: scale(1.05);
}
/* 文章评价反应区域 */
.waline-comment .wl-reaction {
background-color: rgba(17, 17, 17, 0.3);
border-radius: 12px;
padding: 1rem;
margin-bottom: 1.5rem;
border: 1px solid rgba(70, 70, 70, 0.2);
text-align: center;
}
.waline-comment .wl-reaction-title {
font-size: 1.1rem;
margin-bottom: 1rem;
color: rgba(255, 255, 255, 0.9);
}
.waline-comment .wl-reaction-list {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.waline-comment .wl-reaction-item {
background-color: rgba(30, 30, 30, 0.5);
border-radius: 8px;
margin: 5px;
transition: all 0.3s ease;
cursor: pointer;
border: 1px solid rgba(70, 70, 70, 0.2);
/* overflow: hidden; */
}
.waline-comment .wl-reaction-item:hover {
transform: translateY(-3px);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
background-color: rgba(40, 40, 40, 0.8);
border-color: rgba(1, 162, 190, 0.3);
}
.waline-comment .wl-reaction-img {
padding: 6px;
}
.waline-comment .wl-reaction-img img {
transition: transform 0.3s ease;
}
.waline-comment .wl-reaction-item:hover .wl-reaction-img img {
transform: scale(1.15);
}
.waline-comment .wl-reaction-votes {
font-size: 0.8rem;
padding: 5px 0;
background-color: rgba(1, 162, 190, 0.7);
color: #fff;
}
/* 评论计数和排序 */
.waline-comment .wl-meta-head {
margin-bottom: 1.2rem;
border-bottom: 1px solid rgba(70, 70, 70, 0.3);
padding-bottom: 0.8rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.waline-comment .wl-count {
font-size: 1.1rem;
font-weight: 500;
color: rgba(255, 255, 255, 0.9);
}
.waline-comment .wl-sort {
display: flex;
gap: 1rem;
}
.waline-comment .wl-sort li {
cursor: pointer;
transition: all 0.2s ease;
color: rgba(255, 255, 255, 0.7);
}
.waline-comment .wl-sort li:hover {
color: rgba(255, 255, 255, 0.9);
}
.waline-comment .wl-sort li.active {
color: rgba(1, 162, 190, 1);
font-weight: 500;
}
/* 页码导航 */
.waline-comment .wl-page {
margin-top: 1.2rem;
text-align: center;
}
.waline-comment .wl-page button {
background: rgba(30, 30, 30, 0.5);
color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(70, 70, 70, 0.3);
border-radius: 6px;
margin: 0 5px;
padding: 5px 10px;
transition: all 0.2s ease;
}
.waline-comment .wl-page button:hover:not(:disabled) {
background: rgba(1, 162, 190, 0.7);
color: #fff;
transform: translateY(-2px);
}
.waline-comment .wl-page button.active {
background: rgba(1, 162, 190, 0.8);
color: #fff;
}
/* Waline底部版权信息 */
.waline-comment .wl-power {
opacity: 0.6;
font-size: 0.85rem;
margin-top: 2rem;
text-align: center;
}
.waline-comment .wl-power a {
color: rgba(1, 162, 190, 0.9);
text-decoration: none;
transition: all 0.2s ease;
}
.waline-comment .wl-power a:hover {
color: rgba(1, 162, 190, 1);
text-decoration: underline;
}
/* 评论为空状态 */
.waline-comment .wl-empty {
text-align: center;
padding: 2rem 0;
color: rgba(255, 255, 255, 0.6);
font-size: 1.1rem;
}
/* 支持文字数量统计 */
.waline-comment .wl-text-number {
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.6);
}
/* 添加动画效果 */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 响应式调整 */
@media (max-width: 768px) {
.waline-comment-container {
padding: 1.5rem;
margin-top: 2rem;
}
.waline-comment-title {
font-size: 1.8rem;
}
.waline-comment .wl-panel {
padding: 0.8rem;
}
.waline-comment .wl-header {
flex-direction: column;
}
.waline-comment .wl-header-item {
width: 100%;
margin-bottom: 0.5rem;
}
}
@media (max-width: 480px) {
.waline-comment-container {
padding: 1rem;
margin-top: 1.5rem;
}
.waline-comment-title {
font-size: 1.6rem;
}
.waline-comment .wl-reaction-list {
gap: 5px;
}
.waline-comment .wl-card {
padding: 1rem;
}
.waline-comment .wl-meta-head {
flex-direction: column;
gap: 0.5rem;
align-items: flex-start;
}
}
</style> | 2303_806435pww/stalux_moved | src/components/comments/WalineComment.vue | Vue | mit | 10,408 |
---
import { config_site } from '../../utils/config-adapter';
import { Image } from 'astro:assets';
import avatar from '../../images/avatar.webp'
interface Props {
avatarPath: any; // 接受任何图像类型
avatarWidth?: number;
avatarHeight?: number;
author?: string;
}
const {
avatarPath,
avatarWidth = 100,
avatarHeight = 100,
author = config_site.author
} = Astro.props;
// 定义不同设备的图像尺寸
const mobileSizes = 70; // 移动设备图片尺寸
const tabletSizes = 80; // 平板设备图片尺寸
const desktopSizes = 100; // 桌面设备图片尺寸
import '../../styles/components/others/AuthorCard.styl';
---
<div class="card">
<div class="author">
<div class="avatar-container">
{(typeof avatarPath === 'string' && avatarPath!=='') ? (
<img
src={avatarPath}
alt={`${author} avatar`}
class="avatar"
width={avatarWidth}
height={avatarHeight}
loading="eager"
decoding="async"
srcset={`${avatarPath}?w=${mobileSizes} ${mobileSizes}w,
${avatarPath}?w=${tabletSizes} ${tabletSizes}w,
${avatarPath}?w=${desktopSizes} ${desktopSizes}w`}
sizes="(max-width: 480px) ${mobileSizes}px,
(max-width: 768px) ${tabletSizes}px,
${desktopSizes}px"
/>
) : (
<Image
src={avatar}
alt={`${author} avatar`}
class="avatar"
width={avatarWidth}
height={avatarHeight}
densities={[1, 1.5, 2]}
loading="eager"
/>
)}
</div>
<div class="author-info">
<div class="name"><h2>{author}</h2></div>
<slot name="description" />
</div>
<slot name="social-links" />
</div>
</div>
| 2303_806435pww/stalux_moved | src/components/others/AuthorCard.astro | Astro | mit | 1,818 |
---
const { title, author, url } = Astro.props;
import '../../styles/components/others/cc.styl';
// 导入官方CC图标
import ccIcon from '../../images/cc-icons/cc.svg?raw';
import byIcon from '../../images/cc-icons/by.svg?raw';
import ncIcon from '../../images/cc-icons/nc.svg?raw';
import saIcon from '../../images/cc-icons/sa.svg?raw';
---
<div class="cc-by-nc-sa-box">
<div class="cc-content">
<h2 class="cc-title">{title}</h2>
<p class="cc-author">作者: {author}</p>
{url && <p class="cc-url">本文链接: <a href={url} target="_blank" rel="noopener noreferrer">{url}</a></p>}
<p class="cc-license">
本文采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener noreferrer">知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a> 进行许可。
</p>
</div> <div class="cc-watermark">
<div class="tool-icons">
<!-- 官方CC Logo -->
<div class="cc-icon" set:html={ccIcon}></div>
<!-- 官方BY (Attribution) -->
<div class="cc-icon" set:html={byIcon}></div>
<!-- 官方NC (Non-Commercial) -->
<div class="cc-icon" set:html={ncIcon}></div>
<!-- 官方SA (Share Alike) -->
<div class="cc-icon" set:html={saIcon}></div>
</div>
</div>
</div>
| 2303_806435pww/stalux_moved | src/components/others/CC.astro | Astro | mit | 1,308 |
<template>
<div class="clock-container" ref="clockContainer">
<div class="date" v-if="showDate" :style="dateStyle">{{ formattedDate }}</div>
<div class="clock" :style="clockStyle">{{ formattedTime }}</div>
</div>
</template>
<script setup vapor>
import { ref, computed, onBeforeUnmount, watchEffect, onMounted } from 'vue';
/**
* Clock Component Props:
*
* @prop {Boolean} showDate - 控制是否显示日期,默认为false,仅显示时间
* @prop {String} format - 时间显示格式,可选值:
* - 'default': 使用浏览器默认的本地化时间格式
* - '24hour': 使用24小时制显示时间 (如: 14:30:45)
* - '12hour': 使用12小时制显示时间 (如: 下午2:30:45)
* @prop {Number} updateInterval - 时钟更新频率,单位为毫秒,默认1000ms(1秒)
* 可根据需求调整,值越小更新越频繁
*/
const props = defineProps({
showDate: {
type: Boolean,
default: false
},
format: {
type: String,
default: 'default' // 'default', '24hour', '12hour'
},
updateInterval: {
type: Number,
default: 1000 // 默认1秒更新一次
}
});
// 初始值为空或固定值,避免服务器和客户端渲染不一致
const time = ref(new Date('2000-01-01T00:00:00'));
let timer = null;
// 容器引用和尺寸状态
const clockContainer = ref(null);
const containerWidth = ref(0);
let resizeObserver = null;
// 根据容器宽度计算字体大小
const clockStyle = computed(() => {
// 基础字体大小调整因子
const fontSize = calculateFontSize(containerWidth.value, 3.0, 1.5);
return {
fontSize: `${fontSize}rem`,
// 保持其他样式不变
fontWeight: 'normal',
textShadow: '0.1rem 0.1rem 0.2rem rgb(1, 162, 190)',
textAlign: 'center',
whiteSpace: 'nowrap'
};
});
const dateStyle = computed(() => {
// 日期字体稍小一些
const fontSize = calculateFontSize(containerWidth.value, 1.8, 0.9);
return {
fontSize: `${fontSize}rem`,
marginBottom: `${fontSize * 0.3}rem`,
textShadow: '0.1rem 0.1rem 0.2rem rgb(1, 162, 190)',
textAlign: 'center',
whiteSpace: 'nowrap'
};
});
// 根据容器宽度计算字体大小的函数
function calculateFontSize(width, maxSize, minSize) {
if (!width) return maxSize; // 默认值
// 设定边界值
const maxWidth = 600; // 最大宽度,超过此宽度使用最大字体
const minWidth = 150; // 最小宽度,低于此宽度使用最小字体
if (width >= maxWidth) return maxSize;
if (width <= minWidth) return minSize;
// 线性插值计算合适的字体大小
const ratio = (width - minWidth) / (maxWidth - minWidth);
const fontSize = minSize + ratio * (maxSize - minSize);
// 保留一位小数
return Math.round(fontSize * 10) / 10;
}
// 格式化时间显示
const formattedTime = computed(() => {
if (props.format === '24hour') {
return time.value.toLocaleTimeString('zh-CN', { hour12: false });
} else if (props.format === '12hour') {
return time.value.toLocaleTimeString('zh-CN', { hour12: true });
} else {
return time.value.toLocaleTimeString();
}
});
// 格式化日期显示
const formattedDate = computed(() => {
return time.value.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
});
});
function updateTime() {
time.value = new Date();
}
function updateContainerWidth() {
if (clockContainer.value) {
containerWidth.value = clockContainer.value.offsetWidth;
}
}
// 使用 onMounted 钩子,确保只在客户端执行
onMounted(() => {
// 组件挂载后更新时间
updateTime();
// 创建定时器
timer = setInterval(updateTime, props.updateInterval);
// 如果updateInterval属性变化,重新设置定时器
watchEffect(() => {
if (timer) {
clearInterval(timer);
}
timer = setInterval(updateTime, props.updateInterval);
});
// 初始获取容器宽度
updateContainerWidth();
// 创建ResizeObserver监视容器尺寸变化
if (window.ResizeObserver) {
resizeObserver = new ResizeObserver(entries => {
for (const entry of entries) {
if (entry.target === clockContainer.value) {
containerWidth.value = entry.contentRect.width;
}
}
});
if (clockContainer.value) {
resizeObserver.observe(clockContainer.value);
}
} else {
// 降级方案:监听window的resize事件
window.addEventListener('resize', updateContainerWidth);
}
});
onBeforeUnmount(() => {
// 组件卸载前清除定时器
if (timer) {
clearInterval(timer);
timer = null;
}
// 清除ResizeObserver
if (resizeObserver && clockContainer.value) {
resizeObserver.unobserve(clockContainer.value);
resizeObserver.disconnect();
resizeObserver = null;
} else {
// 如果使用的是降级方案
window.removeEventListener('resize', updateContainerWidth);
}
});
</script>
<style scoped>
.clock-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
padding: 10px 0;
overflow: hidden;
}
/* 基础样式 - 将大部分样式转移到了动态计算的style中 */
.clock {
font-weight: normal;
text-align: center;
white-space: nowrap;
}
.date {
text-align: center;
white-space: nowrap;
}
/* 保留媒体查询以支持不支持ResizeObserver的浏览器作为后备方案 */
@media (max-width: 1200px) {
/* 媒体查询样式会被内联样式覆盖 */
}
</style>
| 2303_806435pww/stalux_moved | src/components/others/Clock.vue | Vue | mit | 5,951 |
---
import '../../styles/components/RandomPosts.styl';
// 组件参数定义
interface Props {
count?: number; // 显示随机文章的数量
title?: string; // 组件标题
className?: string; // 自定义CSS类名
delay?: string; // 动画延迟类
}
const {
count = 5,
title = "随机文章",
className = "random-posts",
delay = "delay-300"
} = Astro.props;
---
<div class={`sidebar-section ${className} fade-in-left ${delay}`} id="random-posts-container">
<div class="random-posts-header">
<h3>{title}</h3>
<button
id="refresh-random-posts"
class="refresh-button"
title="刷新随机文章"
aria-label="刷新随机文章">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2"/>
</svg>
</button>
</div>
<ul class="random-posts-list" id="random-posts-list">
<li class="random-post-item loading">
<span>正在加载随机文章...</span>
</li>
</ul>
</div>
<script define:vars={{count}}>
// 从 JSON API 获取文章数据
async function fetchAllPosts() {
try {
const response = await fetch('/allpost.json');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.Posts || [];
} catch (error) {
console.error('Failed to fetch posts:', error);
return [];
}
}
// Fisher-Yates 洗牌算法
function shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
// 生成随机文章HTML
function generatePostsHTML(posts) {
if (posts.length === 0) {
return '<li class="no-posts">暂无文章</li>';
}
return posts.map(post => `
<li class="random-post-item">
<a href="${post.link}" class="random-post-link">
${post.title}
</a>
</li>
`).join('');
}
// 刷新随机文章列表
async function refreshRandomPosts() {
const randomPostsList = document.getElementById('random-posts-list');
if (!randomPostsList) return;
// 添加淡出效果
randomPostsList.classList.add('fade-out');
setTimeout(async () => {
try {
// 从 API 获取最新文章数据
const allPosts = await fetchAllPosts();
if (allPosts.length === 0) {
randomPostsList.innerHTML = '<li class="no-posts">暂无文章</li>';
return;
}
// 获取新的随机文章
const shuffledPosts = shuffleArray(allPosts);
const newRandomPosts = shuffledPosts.slice(0, count);
// 更新DOM
randomPostsList.innerHTML = generatePostsHTML(newRandomPosts);
} catch (error) {
console.error('Error refreshing random posts:', error);
randomPostsList.innerHTML = '<li class="error">加载失败,请重试</li>';
}
// 添加淡入效果
randomPostsList.classList.remove('fade-out');
randomPostsList.classList.add('fade-in');
// 移除淡入动画类
setTimeout(() => {
randomPostsList.classList.remove('fade-in');
}, 500);
}, 300);
}
// 初始化随机文章列表
async function initRandomPosts() {
const randomPostsList = document.getElementById('random-posts-list');
if (!randomPostsList) return;
try {
const allPosts = await fetchAllPosts();
if (allPosts.length === 0) {
randomPostsList.innerHTML = '<li class="no-posts">暂无文章</li>';
return;
}
// 获取初始随机文章
const shuffledPosts = shuffleArray(allPosts);
const initialRandomPosts = shuffledPosts.slice(0, count);
// 更新DOM
randomPostsList.innerHTML = generatePostsHTML(initialRandomPosts);
} catch (error) {
console.error('Error initializing random posts:', error);
randomPostsList.innerHTML = '<li class="error">加载失败</li>';
}
}
// 初始化刷新按钮事件
document.addEventListener('DOMContentLoaded', () => {
// 仅设置刷新按钮事件,不立即加载文章
const refreshButton = document.getElementById('refresh-random-posts');
if (refreshButton) {
refreshButton.addEventListener('click', (e) => {
e.preventDefault();
// 添加旋转动画
refreshButton.classList.add('rotating');
// 刷新文章列表
refreshRandomPosts();
// 移除旋转动画
setTimeout(() => {
refreshButton.classList.remove('rotating');
}, 600);
});
}
});
// 等待页面完全加载后再初始化随机文章列表
window.addEventListener('load', () => {
// 页面完全加载后初始化随机文章列表
initRandomPosts();
});
</script> | 2303_806435pww/stalux_moved | src/components/others/RandomPosts.astro | Astro | mit | 4,962 |
---
/**
* SocialLinks 社交媒体链接组件
*
* 使用 simple-icons 库实现按需导入和构建时优化
* 在 Astro 中,可以充分利用静态站点生成的特点,
* 仅导入实际使用的图标,减小最终打包体积
*/
// 导入 simple-icons 中需要使用的特定图标
import type { SimpleIcon } from 'simple-icons';
import * as simpleIcons from 'simple-icons';
import type { MediaLink } from '../../types';
interface Props {
mediaLinks: MediaLink[];
ariaLabel?: string;
}
const { mediaLinks = [], ariaLabel = "Social Media Links" } = Astro.props;
// 在构建时获取图标
function getIconByTitle(iconName: string): SimpleIcon | undefined {
// 处理特殊情况
if (iconName === 'x-twitter') {
return simpleIcons.siX;
}
// 标准化名称为 simple-icons 的格式 (去除非字母数字字符,转换为小写)
const normalizedName = iconName.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
// 尝试使用 simple-icons 的命名约定获取图标
const iconKey = `si${normalizedName.charAt(0).toUpperCase() + normalizedName.slice(1)}`;
return (simpleIcons as any)[iconKey];
}
import '../../styles/components/others/SocialLinks.styl';
---
<div class="social-links" aria-label={ariaLabel}>
<ul>
{mediaLinks.map((item) => {
const icon = item.icon ? getIconByTitle(item.icon) : undefined;
return (
<li class="socila_icon">
<a
href={item.url}
target="_blank"
aria-label={item.title}
rel="noopener noreferrer"
title={item.title}
>
{icon ? (
<div class="icon-container">
<svg
role="img"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
aria-hidden="true"
>
<title>{icon.title}</title>
<path d={icon.path}></path>
</svg>
</div>
) : (
<span class="custom-icon">{item.icon ? item.icon.charAt(0).toUpperCase() : ''}</span>
)}
<span class="sr-only">{item.title}</span>
</a>
</li>
);
})}
</ul>
</div>
<script>
import { animate } from 'animejs';
document.addEventListener('DOMContentLoaded', () => {
animate('.socila_icon',{
y: [
{ to: '-2.75rem', ease: 'outExpo', duration: 600 },
{ to: 0, ease: 'outBounce', duration: 800, delay: 100 }
],
rotate: {
from: '-1turn',
delay: 0
},
delay: (_, i) => i * 50, // Function based value
ease: 'inOutCirc',
loopDelay: 1000,
loop: true
});
});
</script> | 2303_806435pww/stalux_moved | src/components/others/SocialLinks.astro | Astro | mit | 2,825 |
---
// 标签组件
import { getCollection } from 'astro:content';
import { processFrontmatter } from '../../integrations/process-frontmatter';
const { tags = [] as string[] } = Astro.props;
// 获取所有文章并统计标签数量
const allPosts = await getCollection('posts');
const processedPosts = await Promise.all(allPosts.map(post => processFrontmatter(post)));
// 统计所有标签的文章数量
const tagCounts = new Map<string, number>();
processedPosts.forEach(post => {
const postTags = post.data.tags || [];
postTags.forEach((tag: string) => {
if (tag && tag.trim()) {
tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
}
});
});
import '../../styles/components/others/Tags.styl';
---
<!-- 文章标签部分 -->
<div class="sidebar-section tags">
<div class="section-header">
<h3>文章标签</h3>
<button id="tags-toggle" class="section-toggle" aria-label="折叠标签">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
<path fill="currentColor" d="M7 10l5 5 5-5z"></path>
</svg>
</button>
</div> <div id="tags-content" class="section-content">
<div class="tag-cloud">
{tags && tags.length > 0 ? (
tags.map((tag: string) => (
<a href={`/tags/${tag}/`} class="tag">
<span class="tag-name">{tag}</span>
<span class="tag-count">({tagCounts.get(tag) || 0})</span>
</a>
))
) : (
<div class="no-tags">暂无标签</div>
)}
</div>
</div>
</div>
<script>
// 标签折叠/展开功能
document.addEventListener('DOMContentLoaded', () => {
const toggleBtn = document.getElementById('tags-toggle');
const contentEl = document.getElementById('tags-content');
if (toggleBtn && contentEl) {
toggleBtn.addEventListener('click', () => {
const isCollapsing = !contentEl.classList.contains('collapsed');
if (isCollapsing) {
// 快速折叠 (250ms)
contentEl.style.transition = 'max-height 0.25s ease, opacity 0.25s ease';
} else {
// 缓慢展开 (600ms)
contentEl.style.transition = 'max-height 0.6s ease, opacity 0.6s ease';
}
contentEl.classList.toggle('collapsed');
toggleBtn.classList.toggle('collapsed');
});
}
});
</script> | 2303_806435pww/stalux_moved | src/components/others/Tags.astro | Astro | mit | 2,371 |
---
// 在 Astro 中,前端脚本和逻辑放在 frontmatter 中(三个破折号之间)
import { config_site } from "../../utils/config-adapter";
// 从配置中获取文本内容
const texts = config_site.textyping || ['Hello World!'];
// 在服务器端,我们只需要准备数据,而不需要操作 DOM
---
<div id="textyping"></div>
<script define:vars={{ texts: texts }}>
// 这里是客户端脚本,使用define:vars将服务器端的texts变量传递给客户端脚本
// 状态变量
let displayText = '';
let currentTextIndex = Math.floor(Math.random() * texts.length);
let currentCharIndex = 0;
let isDeleting = false;
let typingDelay = 40; // 打印速度
let deletingDelay = 80; // 删除速度
let pauseDelay = 1000; // 暂停时间
const textElement = document.getElementById('textyping');
// 打字效果函数
function typeText() {
if (!textElement) return;
const currentText = texts[currentTextIndex];
if (isDeleting) {
displayText = currentText.slice(0, currentCharIndex--);
textElement.textContent = displayText;
typingDelay = deletingDelay;
if (currentCharIndex < 0) {
isDeleting = false;
let newIndex;
do {
newIndex = Math.floor(Math.random() * texts.length);
} while (newIndex === currentTextIndex && texts.length > 1);
currentTextIndex = newIndex;
setTimeout(typeText, pauseDelay);
return;
}
} else {
displayText = currentText.substring(0, currentCharIndex++);
textElement.textContent = displayText;
typingDelay = 80;
if (currentCharIndex > currentText.length) {
isDeleting = true;
currentCharIndex = currentText.length;
setTimeout(typeText, pauseDelay);
return;
}
}
setTimeout(typeText, typingDelay);
}
// 在DOM加载完成后启动打字效果
document.addEventListener('DOMContentLoaded', () => {
typeText();
});
</script>
<style>
#textyping {
position: relative;
text-align: center;
font-size: 2.5rem;
margin: 20px auto;
width: 90%;
max-width: 800px;
min-height: 2rem;
padding: 0 15px;
color: #ffffff;
text-shadow: 0.1rem 0.1rem 0.2rem rgb(1, 162, 190);
overflow-wrap: break-word;
word-wrap: break-word;
hyphens: auto;
}
#textyping::after {
content: '|';
position: relative;
animation: blink 1s infinite;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
/* 响应式调整 */
@media (max-width: 768px) {
#textyping {
font-size: 2rem;
margin: 15px auto;
}
}
@media (max-width: 480px) {
#textyping {
font-size: 1.5rem;
margin: 10px auto;
}
}
</style> | 2303_806435pww/stalux_moved | src/components/others/TextTyping.astro | Astro | mit | 2,826 |
<template>
<div id="textyping">{{ displayText }}</div>
</template>
<script setup vapor>
import { onMounted, ref, computed } from 'vue';
import { config_site } from "../../utils/config-adapter";
// 获取配置的文字
const texts = computed(() => config_site.textyping);
// 状态变量
const displayText = ref('');
let currentTextIndex = Math.floor(Math.random() * texts.value.length);
let currentCharIndex = 0;
let isDeleting = false;
let typingDelay = 40; // 打印速度
let deletingDelay = 80; // 删除速度
let pauseDelay = 1000; // 暂停时间
// 打字效果函数
function typeText() {
const currentText = texts.value[currentTextIndex];
if (isDeleting) {
displayText.value = currentText.slice(0, currentCharIndex--);
typingDelay = deletingDelay;
if (currentCharIndex < 0) {
isDeleting = false;
let newIndex;
do {
newIndex = Math.floor(Math.random() * texts.value.length);
} while (newIndex === currentTextIndex && texts.value.length > 1);
currentTextIndex = newIndex;
setTimeout(typeText, pauseDelay);
return;
}
} else {
displayText.value = currentText.substring(0, currentCharIndex++);
typingDelay = 80;
if (currentCharIndex > currentText.length) {
isDeleting = true;
currentCharIndex = currentText.length;
setTimeout(typeText, pauseDelay);
return;
}
}
setTimeout(typeText, typingDelay);
}
// 组件加载时启动打字效果
onMounted(() => {
typeText();
});
</script>
<style scoped>
#textyping {
position: relative;
text-align: center;
font-size: 2.5rem;
margin: 20px auto;
width: 90%;
max-width: 800px;
min-height: 2rem;
padding: 0 15px;
color: #ffffff;
text-shadow: 0.1rem 0.1rem 0.2rem rgb(1, 162, 190);
overflow-wrap: break-word;
word-wrap: break-word;
hyphens: auto;
}
#textyping::after {
content: '|';
position: relative;
animation: blink 1s infinite;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
/* 响应式调整 */
@media (max-width: 768px) {
#textyping {
font-size: 2rem;
margin: 15px auto;
}
}
@media (max-width: 480px) {
#textyping {
font-size: 1.5rem;
margin: 10px auto;
}
}
</style> | 2303_806435pww/stalux_moved | src/components/others/TextTyping.vue | Vue | mit | 2,438 |
import type { SiteConfig, BadgeOptions } from './types';
export const site: SiteConfig = {
/**
* 核心站点信息
*/
title: 'Stalux博客主题',
titleDefault: 'Stalux博客主题',
siteName: 'Stalux博客主题',
author: 'xingwangzhe',
/**
* SEO 核心配置
*/
description: '博客主题Stalux - 为内容创作者提供的专业展示平台,支持多种自定义功能,包含评论系统集成、友情链接管理、社交媒体分享和丰富的SEO优化选项,让您的内容更具吸引力和可发现性。',
short_description: "博客主题Stalux",
url: 'https://stalux.needhelp.icu',
keywords: 'Stalux, 博客主题, 内容创作, Astro主题, 静态网站生成器, SEO优化, 自定义博客, 响应式设计, 评论系统, 前端开发, Astro',
lang: 'zh-CN',
locale: 'zh_CN',
canonical: 'https://stalux.needhelp.icu',
/**
* 站点资源配置
*/
favicon: '',
avatarPath: '',
/**
* <head>元素硬嵌入
*/
head: `<meta name="nishia" content="nihaiso">
<script>console.log("欢迎使用Stalux主题")</script>`,
/**
* 站点导航配置
*/
nav: [
{ title: '首页', path: '/', icon: 'home' },
{ title: '归档', path: '/archives/', icon: 'archive' },
{ title: '分类', path: '/categories/', icon: 'folder' },
{ title: '标签', path: '/tags/', icon: 'tag' },
{ title: '友链', path: '/links/', icon: 'link' },
{ title: '关于', path: '/about/', icon: 'user' }
],
/**
* 站点特效配置
*/
textyping: [
'Free for free, not free for charge!',
'任意键在哪?',
'F12看看?',
'Hello World!'
],
/**
* 评论系统配置
*/
comment: {
waline: {
serverURL: 'https://waline.xingwangzhe.fun', // 你的Waline服务器地址 //我加白名单了,别让我在日志里逮到你用(╯▔皿▔)╯
lang: 'zh-CN', // 语言设置
emoji: ['https://unpkg.com/@waline/emojis@1.1.0/weibo'], // 表情包设置
requiredFields: [], // 必填项
reaction: false, // 文章反应
meta: ['nick', 'mail', 'link'], // 评论者的元数据
wordLimit: 200, // 字数限制
pageSize: 10 // 评论分页大小
}
},
/**
* 社交媒体链接配置
*/
medialinks: [
{ title: 'Github', url: 'https://github.com/xingwangzhe/stalux', icon: 'github' },
{ title: 'Bilibili', url: 'https://space.bilibili.com/', icon: 'bilibili' },
{ title: 'Twitter', url: 'https://x.com/', icon: 'x-twitter' },
{ title: 'Weibo', url: 'https://weibo.com/', icon: 'sinaweibo' },
{ title: 'QQ', url: 'https://qm.qq.com/', icon: 'qq' },
{ title: 'Telegram', url: 'https://t.me/', icon: 'telegram' },
{ title: 'Discord', url: 'https://discord.gg/', icon: 'discord' },
],
/**
* 友情链接配置
*/
friendlinks_title: '帮助链接',
friendlinks_description: '下列站点对本主题的开发起到了关键作用,非常感谢它们的资料',
friendlinks: [
{
title: 'Astro',
url: 'https://astro.build/',
avatar: 'https://astro.build/favicon.svg',
description: 'The web framework for content-driven websites'
},
{
title: 'Vue',
url: 'https://cn.vuejs.org/',
avatar: 'https://cn.vuejs.org/logo.svg',
description: '易学易用,性能出色,适用场景丰富的 Web 前端框架。'
},
{
title: 'MDN Web Docs',
url: 'https://developer.mozilla.org/',
avatar: 'https://developer.mozilla.org/favicon.ico',
description: 'Documenting web technologies, including CSS, HTML, and JavaScript, since 2005.'
},
{
title: 'Simple Icons',
url: 'https://simpleicons.org/',
avatar: 'https://simpleicons.org/favicon.ico',
description: '流行品牌的 3282 SVG 图标'
},
{
title: 'Feather',
url: 'https://feathericons.com/',
avatar: 'https://feathericons.com/favicon.ico',
description: 'Beautifully simple open-source icons'
}
],
/**
* 页脚配置
* 整合所有页脚相关设置,便于管理
*/
footer: {
// 站点构建时间,用于计算运行时长
buildtime: '2025-05-01T10:00:00', // 站点构建时间,推荐使用ISO 8601标准格式(YYYY-MM-DDTHH:MM:SS)
// 版权信息
copyright: {
enabled: true, // 是否启用版权信息
startYear: 2024, // 可选:起始年份,如设置为2024,则显示2024-2025
customText: '' // 可选:自定义版权文本,如为空则使用默认格式
},
// 主题信息
theme: {
showPoweredBy: true, // 是否显示"Powered by Astro"
showThemeInfo: true // 是否显示"Theme is Stalux"
},
// 备案信息
beian: {
// ICP备案
icp: {
enabled: false, // 是否启用ICP备案显示
number: '辽ICP备XXXXXXXX号' // ICP备案号,如不需要可留空
},
// 公安备案
security: {
enabled: false, // 是否启用公安备案显示
text: '辽公网安备 XXXXXXXXXXXX号', // 公安备案号文字
number: 'XXXXXXXXXXXX' // 公安备案号数字部分(用于链接跳转)
}
},
// 徽章配置
badges: [
{
label: 'Built with',
message: '❤',
color: 'red',
style: 'for-the-badge',
alt: 'Built with Love',
href: 'https://github.com/xingwangzhe'
},
{
label: 'Powered by',
message: 'Astro',
color: 'orange',
style: 'flat-square',
alt: 'Powered by Astro',
href: 'https://astro.build/'
},
{
label: 'Theme',
message: 'Stalux',
color: 'blueviolet',
alt: 'Theme: Stalux',
href: 'https://github.com/xingwangzhe/stalux'
},
{
label: 'license',
message: 'MIT',
color: 'blue',
alt: 'License: MIT',
href: 'https://github.com/xingwangzhe/stalux/blob/main/LICENSE'
},
{
label: '开往🚆',
message: '友链接力',
color: 'green',
alt: '开往-友链接力',
href: 'https://www.travellings.cn/go.html'
},
{
label: '大佬论坛',
message: '',
color: 'yellowgreen',
alt: '大佬论坛',
href: 'https://www.dalao.net/'
},
{
label: 'BlogFinder',
message: '',
color: 'purple',
alt: 'BlogFinder',
href: 'https://bf.zzxworld.com/'
},
{
label: '空间穿梭',
message: '',
color: 'teal',
alt: '空间穿梭-随机访问BlogsClub成员博客',
href: 'https://www.blogsclub.org/go'
},
{
label: '多吉云',
message: 'CDN',
color: 'lightblue',
alt: '多吉云CDN',
href: 'https://www.dogecloud.com/?iuid=11702'
},
{
label: '十年之约',
message: '',
color: 'brightgreen',
alt: '十年之约',
href: 'https://www.foreverblog.cn/blog/6304.html'
},
{
label: '博客宇宙',
message: '',
color: 'darkblue',
alt: '博客宇宙',
href: 'https://blogverse.cn/'
}
] as BadgeOptions[]
}
}
| 2303_806435pww/stalux_moved | src/consts.ts | TypeScript | mit | 7,280 |
import { glob } from 'astro/loaders';
import { defineCollection, z } from 'astro:content';
const posts = defineCollection({
loader: glob({ base: './src/content/posts', pattern: '**/*.{md,mdx}' }),
schema: z.object({
title: z.string(),
// 接受日期字符串或 Date 对象
date: z.union([z.string(), z.coerce.date()]).optional(),
// 更新时间可选,接受日期字符串或 Date 对象
updated: z.union([z.string(), z.coerce.date()]).optional(),
// 自定义描述字段,用于 SEO
description: z.string().optional(),
// 摘要字段,如果没有描述,则用作备选
excerpt: z.string().optional(),
// 文章封面图
cover: z.string().optional(), // 文章作者
author: z.string().optional(),
tags: z.array(z.string()).optional(),
categories: z.array(z.string()).optional(), // 分类改为平铺标签列表,每个分类都是独立的字符串
abbrlink: z.union([z.string(), z.number()]).optional(),
// 是否不被搜索引擎索引
noindex: z.boolean().optional().default(false),
}),
});
// 添加 about 集合
const about = defineCollection({
loader: glob({ base: './src/content/about', pattern: '**/*.{md,mdx}' }),
schema: z.object({
title: z.string(),
priority: z.number().default(1), // 优先级,数字越大优先级越高
}),
});
export const collections = { posts, about };
| 2303_806435pww/stalux_moved | src/content.config.ts | TypeScript | mit | 1,404 |
import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync } from 'fs';
import { join, dirname, relative } from 'path';
import { fileURLToPath } from 'url';
// 获取当前文件的目录
const __dirname = dirname(fileURLToPath(import.meta.url));
// 时间戳数据的存储路径
const TIMESTAMP_FILE = join(process.cwd(), 'file-timestamps.json');
// 缓存的时间戳数据,避免重复读取文件
let cachedTimestamps = null;
/**
* 加载现有的时间戳数据
* 在开发环境下每次都读取文件,确保数据最新
* 在构建环境下使用缓存数据避免多次读取
*/
export function loadTimestamps() {
// 如果是构建环境且已有缓存数据,直接返回缓存
if (process.env.NODE_ENV === 'production' && cachedTimestamps) {
return cachedTimestamps;
}
if (existsSync(TIMESTAMP_FILE)) {
try {
const data = JSON.parse(readFileSync(TIMESTAMP_FILE, 'utf-8'));
// 缓存数据
cachedTimestamps = data;
return data;
} catch (e) {
console.warn('无法解析时间戳文件,将创建新文件', e);
}
}
return {};
}
/**
* 保存时间戳数据
* 在构建环境中,不写入文件,只更新内存中的缓存
*/
export function saveTimestamps(timestamps) {
// 在构建环境中不修改文件
if (process.env.NODE_ENV === 'production' || process.env.VERCEL === '1') {
console.log('[timestamp] 构建环境下不写入时间戳文件,仅更新内存缓存');
cachedTimestamps = { ...timestamps };
return;
}
try {
// 确保文件所在目录存在
const dir = dirname(TIMESTAMP_FILE);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
// 更新缓存
cachedTimestamps = { ...timestamps };
// 写入文件
writeFileSync(TIMESTAMP_FILE, JSON.stringify(timestamps, null, 2), 'utf-8');
} catch (error) {
console.error('保存时间戳文件时出错:', error);
}
}
/**
* 将时间转换为本机时区时间,并附加时区信息
* @param {Date} date 日期对象
* @returns {string} 带时区信息的时间字符串
*/
function formatDateWithTimezone(date) {
// 获取当前时区偏移(分钟)
const tzOffset = date.getTimezoneOffset();
// 计算时区字符串,如 "+08:00"
const tzSign = tzOffset <= 0 ? "+" : "-";
const tzHours = String(Math.abs(Math.floor(tzOffset / 60))).padStart(2, "0");
const tzMinutes = String(Math.abs(tzOffset % 60)).padStart(2, "0");
const tzString = `${tzSign}${tzHours}:${tzMinutes}`;
// 格式化日期为 "YYYY-MM-DDThh:mm:ss.sss+HH:MM" 格式
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
const milliseconds = String(date.getMilliseconds()).padStart(3, "0");
// 返回带时区信息的时间字符串
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${tzString}`;
}
/**
* 初始化文件时间戳
* 如果文件已有时间戳记录,则保留原有记录
* 如果没有时间戳记录,则从文件系统获取时间并记录
* @param {string} filepath 文件绝对路径
* @param {string} [abbrlink] 可选的 abbrlink 值
* @returns {object} 更新后的时间戳对象
*/
export function initFileTimestamp(filepath, abbrlink) {
const timestamps = loadTimestamps();
const relativePath = relative(process.cwd(), filepath).replace(/\\/g, '/');
// 如果文件不存在于记录中,从文件系统获取时间
if (!timestamps[relativePath]) {
try {
const stats = statSync(filepath);
// 优先使用birthtime,如果不可用或为无效日期,则使用ctime
const createTime = stats.birthtime && stats.birthtime.getTime()
? stats.birthtime
: stats.ctime;
// 创建时间戳记录
timestamps[relativePath] = {
created: formatDateWithTimezone(createTime),
modified: formatDateWithTimezone(stats.mtime)
};
// 如果提供了 abbrlink,也保存起来
if (abbrlink) {
timestamps[relativePath].abbrlink = abbrlink;
}
saveTimestamps(timestamps);
} catch (error) {
// 忽略错误
}
} else if (abbrlink && !timestamps[relativePath].abbrlink) {
// 如果文件记录已存在但没有 abbrlink,且提供了 abbrlink,则更新它
timestamps[relativePath].abbrlink = abbrlink;
saveTimestamps(timestamps);
}
return timestamps;
}
/**
* 更新文件的修改时间戳
* @param {string} filepath 文件绝对路径
* @returns {object} 更新后的时间戳对象
*/
export function updateModifiedTimestamp(filepath) {
const timestamps = loadTimestamps();
const relativePath = relative(process.cwd(), filepath).replace(/\\/g, '/');
// 确保文件有初始时间戳
if (!timestamps[relativePath]) {
initFileTimestamp(filepath);
return loadTimestamps();
}
try {
const stats = statSync(filepath); // 更新修改时间,使用本机时区时间
timestamps[relativePath].modified = formatDateWithTimezone(stats.mtime);
saveTimestamps(timestamps);
} catch (error) {
// 忽略错误
}
return timestamps;
}
/**
* 获取指定文件的时间戳
* @param {string} filepath 文件绝对路径
* @returns {object|null} 文件时间戳对象,如果不存在返回null
*/
export function getFileTimestamp(filepath) {
const timestamps = loadTimestamps();
const relativePath = relative(process.cwd(), filepath).replace(/\\/g, '/');
if (!timestamps[relativePath]) {
return null;
}
return timestamps[relativePath];
}
/**
* 清理已删除文件的时间戳记录
* @param {string[]} relativePaths 要清理的文件的相对路径
*/
export function cleanupDeletedFiles(relativePaths) {
const timestamps = loadTimestamps();
let changed = false;
for (const path of relativePaths) {
if (timestamps[path]) {
delete timestamps[path];
changed = true;
}
}
if (changed) {
saveTimestamps(timestamps);
console.log(`已清理 ${relativePaths.length} 个已删除文件的时间戳记录`);
}
return timestamps;
}
/**
* 更新文件的 abbrlink
* @param {string} filepath 文件绝对路径
* @param {string} abbrlink abbrlink 值
* @returns {object} 更新后的时间戳对象
*/
export function updateFileAbbrlink(filepath, abbrlink) {
const timestamps = loadTimestamps();
const relativePath = relative(process.cwd(), filepath).replace(/\\/g, '/');
// 确保文件有初始时间戳
if (!timestamps[relativePath]) {
console.log(`[file-timestamps] 文件 ${relativePath} 没有时间戳记录,初始化...`);
initFileTimestamp(filepath);
}
// 检查是否已有 abbrlink
const hadAbbrlink = timestamps[relativePath] && timestamps[relativePath].abbrlink;
const existingAbbrlink = hadAbbrlink ? timestamps[relativePath].abbrlink : null;
// 更新或添加 abbrlink
if (timestamps[relativePath]) {
if (hadAbbrlink && existingAbbrlink !== abbrlink) {
console.log(`[file-timestamps] 警告: 正在更改文件 ${relativePath} 的 abbrlink 从 ${existingAbbrlink} 到 ${abbrlink}`);
}
timestamps[relativePath].abbrlink = abbrlink;
saveTimestamps(timestamps);
if (!hadAbbrlink) {
console.log(`[file-timestamps] 为文件 ${relativePath} 添加 abbrlink: ${abbrlink}`);
}
}
return timestamps;
}
| 2303_806435pww/stalux_moved | src/integrations/file-timestamps.mjs | JavaScript | mit | 7,680 |