code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
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_5062_4009
tls/record/src/record.h
C
unknown
4,034
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import org.json.JSONArray; import org.json.JSONObject; public class test { static File outPath=new File("sdcard/out"); public static void main(String[] args) throws Exception { outPath.mkdirs(); outfromdata(); System.out.println(); } /* https://products.aspose.app/cells/zh/conversion/xlsx-to-json NDT-1.15.json xlxs2json */ public static void outfromdata() throws Exception { JSONObject js=pare(new File("sdcard/a")); BufferedWriter index=new BufferedWriter(new FileWriter(new File(outPath, "index.md"))); index.write("# index"); JSONArray list= js.getJSONArray("单位代码"); BufferedWriter buff=null; for (int i=0;i < list.length();++i) { JSONObject obj=list.optJSONObject(i); if (obj == null) { if (buff != null) { buff.close(); buff = null; } continue; } String str=obj.optString("key翻译"); if (str == null)continue; String key=obj.optString("key描述解释"); boolean isSection=key == null ?false: key.startsWith("[") && key.endsWith("]"); if (isSection || str.matches("[a-zA-Z]{2,}")) { if (buff != null)buff.close(); if (isSection) { int j=key.indexOf('_'); if (j < 0)j = key.length() - 1; str = key.substring(1, j); } if ("comment".equals(str)) { continue; } index.write("\n## ["); char c=str.charAt(0); if (c >= 'A' && c <= 'Z') { char[] crr=str.toCharArray(); crr[0] = Character.toLowerCase(c); str = new String(crr); } String rstr=str.equals("leg") ?"leg/arm": str.equals("global") ?"global_resource": str.equals("action") ?"action/hiddenAction": str; index.write(rstr); index.write("]("); index.write(str); index.write(".md"); index.write(")\n"); index.write(obj.optString("key代码")); buff = new BufferedWriter(new FileWriter(new File(outPath, str + ".md"))); buff.write("# "); buff.write(rstr); buff.write("\n"); } else if (buff != null) { key = obj.optString("key代码"); if (key == null || key.length() == 0)continue; char c=key.charAt(0); if (Character.isLowerCase(c) || Character.isUpperCase(c) || c == '@') { buff.write("## "); buff.write(key); buff.write("\ntranslation:"); buff.write(str.replaceFirst(":$", "")); buff.write("\n<br>type:"); String type=obj.optString("key值类型", "string"); buff.write(type); String type2=obj.optString("Column8"); if (type2 != null && type2.length() > 0) { if (!type.equals(type2)) { buff.write('/'); buff.write(type2); } } str = obj.optString("key描述解释"); if (str != null) { buff.write("\n<br>"); buff.write(str); } buff.write('\n'); } } } if (buff != null) buff.close(); index.close(); } public static JSONObject pare(File f) throws Exception { FileInputStream fi=new FileInputStream(f); byte[] by=new byte[fi.available()]; fi.read(by); return new JSONObject(new String(by)); } }
2303_806435pww/RW-API-Code_moved
CODE_NDT/test.java
Java
apache-2.0
3,114
import { defineConfig } from 'vitepress' // https://vitepress.dev/reference/site-config export default defineConfig({ title: "RW-API_Code", description: "Easy Code", cleanUrls: true, head: [ ['link', { rel: 'icon', href: '/favicon.ico' }], [ 'script', { src: 'https://cdn.jsdelivr.net/npm/docsify-chat/lib/docsify-chat.min.js' } ] ], themeConfig: { // https://vitepress.dev/reference/default-theme-config nav: [ { text: '主页', link: '/' }, { text: '单位API', link: '/src/Unit/core' }, { text: '地图API', link: '/src/Map/all' }, { text: '编写指南', link: '/api-dev' }, { text: 'RW-Engine指南', link: '/src/RW-Engine/quick-start' }, { text: '感谢名单', link: '/cos' } ], docFooter: { prev: "上一篇文章", next: "下一篇文章", }, sidebar: [ { text: 'RW-API-Code', items: [ { text: '主页-Home', link: '/' }, { text: '-------------------------', link: '' }, { text: '[API-单位组-Unit]', link: '' }, { text: '核心-CORE', link: '/src/Unit/core' }, { text: '可建造-CANBUILD', link: '/src/Unit/canbuild' }, { text: '附属-ATTACHMENT', link: '/src/Unit/attachment' }, { text: '图像-GRAPHICS', link: '/src/Unit/graphics' }, { text: '炮塔-TURRET', link: '/src/Unit/turret' }, { text: '攻击-ATTACK', link: '/src/Unit/attack' }, { text: '运动-MOVEMENT', link: '/src/Unit/movement' }, { text: '逻辑-LOGIC', link: '/src/Unit/loginboolean' }, { text: '资源-RESOURCE', link: '/src/Unit/resource' }, { text: '贴花-DECAL', link: '/src/Unit/decal' }, { text: '刷兵/刷单位-SPAWN', link: '/src/Unit/spawnunit_spawnprojectile' }, { text: '-------------------------', link: '' }, { text: '地图格式', link: '/src/Map/all' }, { text: 'Trigger', link: '/src/Map/trigger' } ] } ], socialLinks: [ { icon: 'github', link: 'https://github.com/LingASDJ/RW-API-Code/' } ], footer: { message: "Spldream Studio", copyright: "Copyright © 2023-2025 RW-API-Code", }, search: { provider: 'local', options: { locales: { zh: { translations: { button: { buttonText: '搜索文档', buttonAriaLabel: '搜索文档', }, modal: { noResultsText: '你干嘛~哎呦~无法找到相关结果', resetButtonTitle: '清除查询条件', footer: { selectText: '选择', navigateText: '切换', closeText: '关闭', closeKeyAriaLabel: '关闭', selectKeyAriaLabel: '选择', navigateUpKeyAriaLabel: '上一个', navigateDownKeyAriaLabel: '下一个' }, backButtonTitle: '返回上一级', displayDetails: '显示详情' } } } }, translations: { button: { buttonText: '搜索文档', buttonAriaLabel: '搜索文档', }, modal: { noResultsText: '无法找到相关结果', resetButtonTitle: '清除查询条件', footer: { selectText: '选择', navigateText: '切换', closeText: '关闭', closeKeyAriaLabel: '关闭', selectKeyAriaLabel: '选择', navigateUpKeyAriaLabel: '上一个', navigateDownKeyAriaLabel: '下一个' }, backButtonTitle: '返回上一级', displayDetails: '显示详情' } } } } } })
2303_806435pww/RW-API-Code_moved
rustedwarfareapicode/.vitepress/config.ts
TypeScript
apache-2.0
3,959
<!--.vitepress/theme/MyLayout.vue--> <script setup> import DefaultTheme from "vitepress/theme"; const { Layout } = DefaultTheme; </script> <template> <Layout> <template #not-found> <!-- 404界面 --> <div data-v-98ddab3d="" data-v-8f7cd5e4="" class="VPContent" id="VPContent" > <div data-v-6c4a3ffe="" data-v-98ddab3d="" class="NotFound"> <img src="/logo.png" alt="" class="notfound-img" /> <p data-v-6c4a3ffe="" class="code">404</p> <h1 data-v-6c4a3ffe="" class="title"> 你干嘛~,这里什么都没有! </h1> <div data-v-6c4a3ffe="" class="divider"></div> <blockquote data-v-6c4a3ffe="" class="quote"> 你寻找的页面可能不存在或被迁移…… </blockquote> <div data-v-6c4a3ffe="" class="action"> <a data-v-6c4a3ffe="" class="link" href="/" aria-label="go to home" > 返回主页 </a> </div> </div> </div> </template> </Layout> </template> <style scoped> .notfound-img { margin: 0 auto; max-width: 256px; } .NotFound { padding: 64px 24px 96px; text-align: center; } .code { line-height: 64px; font-size: 64px; font-weight: 600; } .title { padding-top: 12px; letter-spacing: 2px; line-height: 20px; font-size: 20px; font-weight: 700; } .divider { margin: 24px auto 18px; width: 64px; height: 1px; background-color: rgba(48, 52, 54, 0.12); } .quote { color: var(--darkreader-text--vp-c-text-2); } .quote { margin: 0 auto; max-width: 256px; font-size: 14px; font-weight: 500; color: var(--vp-c-text-2); } .action { padding-top: 20px; } .link { color: #4ff0ba; border: 1px solid #10b981; } .link { display: inline-block; border: 1px solid #10b981; border-radius: 16px; padding: 3px 16px; font-size: 14px; font-weight: 500; color: var(--vp-c-brand); transition: border-color 0.25s, color 0.25s; } </style>
2303_806435pww/RW-API-Code_moved
rustedwarfareapicode/.vitepress/theme/NotFound.vue
Vue
apache-2.0
2,575
// .vitepress/theme/index.js import DefaultTheme from "vitepress/theme"; import "./style/custom.css"; import NotFound from "../theme/NotFound.vue"; /** * 等待指定时间 * @param {number} timeout 等待时间,单位:毫秒 * @returns {Promise<void>} 等待结果 * @example await wait(1000); * @example wait(1000).then(() => console.log("timeout")); */ function wait(timeout) { return new Promise((resolve) => setTimeout(resolve, timeout)); } /** * 请求剪贴板权限 * @returns {Promise<void>} 请求结果 * @example await requestClipboardPermission(); */ async function requestClipboardPermission() { try { await navigator.permissions.query({ name: "clipboard-write" }); } catch (error) { console.error(error); } } /** * 初始化 * @returns {Promise<void>} 初始化结果 * @example await init(); */ async function init() { try { await wait(1000); // console.log("timeout"); const copyBtnList = document.getElementsByClassName("copy"); // console.log(copyBtnList); // console.log(copyBtnList.length); for (let i = 0; i < copyBtnList.length; i++) { const btn = copyBtnList[i]; btn.addEventListener("touchend", async () => { // 请求剪贴板权限 await requestClipboardPermission(); const parentDiv = btn.parentNode; const codeElem = parentDiv.querySelector("code"); const spans = [...codeElem.querySelectorAll("span")]; const textToCopy = [ ...new Set(spans.map((span) => span.textContent)), ].join(""); // console.log(textToCopy); try { await navigator.clipboard.writeText(textToCopy); // console.log("Text copied to clipboard"); } catch (error) { const textarea = document.createElement("textarea"); textarea.value = textToCopy; document.body.appendChild(textarea); textarea.select(); document.execCommand("copy"); document.body.removeChild(textarea); // console.log("Text copied to clipboard"); } }); } } catch (error) { console.error(error); } } init(); export default { ...DefaultTheme, Layout: NotFound, };
2303_806435pww/RW-API-Code_moved
rustedwarfareapicode/.vitepress/theme/index.js
JavaScript
apache-2.0
2,480
/** * Colors: Solid * -------------------------------------------------------------------------- */ :root { --vp-c-white: #ffffff; --vp-c-black: #000000; --vp-c-neutral: var(--vp-c-black); --vp-c-neutral-inverse: var(--vp-c-white); } .dark { --vp-c-neutral: var(--vp-c-white); --vp-c-neutral-inverse: var(--vp-c-black); } /** * Colors: Palette * * The primitive colors used for accent colors. These colors are referenced * by functional colors such as "Text", "Background", or "Brand". * * Each colors have exact same color scale system with 3 levels of solid * colors with different brightness, and 1 soft color. * * - `XXX-1`: The most solid color used mainly for colored text. It must * satisfy the contrast ratio against when used on top of `XXX-soft`. * * - `XXX-2`: The color used mainly for hover state of the button. * * - `XXX-3`: The color for solid background, such as bg color of the button. * It must satisfy the contrast ratio with pure white (#ffffff) text on * top of it. * * - `XXX-soft`: The color used for subtle background such as custom container * or badges. It must satisfy the contrast ratio when putting `XXX-1` colors * on top of it. * * The soft color must be semi transparent alpha channel. This is crucial * because it allows adding multiple "soft" colors on top of each other * to create a accent, such as when having inline code block inside * custom containers. * -------------------------------------------------------------------------- */ :root { --vp-c-gray-1: #dddde3; --vp-c-gray-2: #e4e4e9; --vp-c-gray-3: #ebebef; --vp-c-gray-soft: rgba(142, 150, 170, 0.14); --vp-c-indigo-1: #18794e; --vp-c-indigo-2: #299764; --vp-c-indigo-3: #30a46c; --vp-c-indigo-soft: rgba(16, 185, 129, 0.14); --vp-c-green-1: #18794e; --vp-c-green-2: #299764; --vp-c-green-3: #30a46c; --vp-c-green-soft: rgba(16, 185, 129, 0.14); --vp-c-yellow-1: #915930; --vp-c-yellow-2: #946300; --vp-c-yellow-3: #9f6a00; --vp-c-yellow-soft: rgba(234, 79, 8, 0.14); --vp-c-red-1: #b8272c; --vp-c-red-2: #d5393e; --vp-c-red-3: #e0575b; --vp-c-red-soft: rgba(244, 63, 94, 0.14); --vp-c-sponsor: #db2777; } .dark { --vp-c-gray-1: #515c67; --vp-c-gray-2: #414853; --vp-c-gray-3: #32363f; --vp-c-gray-soft: rgba(101, 117, 133, 0.16); --vp-c-indigo-1: #3dd68c; --vp-c-indigo-2: #30a46c; --vp-c-indigo-3: #298459; --vp-c-indigo-soft: rgba(16, 185, 129, 0.16); --vp-c-green-1: #3dd68c; --vp-c-green-2: #30a46c; --vp-c-green-3: #298459; --vp-c-green-soft: rgba(16, 185, 129, 0.16); --vp-c-yellow-1: #f9b44e; --vp-c-yellow-2: #da8b17; --vp-c-yellow-3: #a46a0a; --vp-c-yellow-soft: rgba(234, 179, 8, 0.16); --vp-c-red-1: #f66f81; --vp-c-red-2: #f14158; --vp-c-red-3: #b62a3c; --vp-c-red-soft: rgba(244, 63, 94, 0.16); } /** * Colors: Background * * - `bg`: The bg color used for main screen. * * - `bg-alt`: The alternative bg color used in places such as "sidebar", * or "code block". * * - `bg-elv`: The elevated bg color. This is used at parts where it "floats", * such as "dialog". * * - `bg-soft`: The bg color to slightly ditinguish some components from * the page. Used for things like "carbon ads" or "table". * -------------------------------------------------------------------------- */ :root { --vp-c-bg: #ffffff; --vp-c-bg-alt: #f6f6f7; --vp-c-bg-elv: #ffffff; --vp-c-bg-soft: #f6f6f7; } .dark { --vp-c-bg: #1b1b1f; --vp-c-bg-alt: #161618; --vp-c-bg-elv: #202127; --vp-c-bg-soft: #202127; } /** * Colors: Borders * * - `divider`: This is used for separators. This is used to divide sections * within the same components, such as having separator on "h2" heading. * * - `border`: This is designed for borders on interactive components. * For example this should be used for a button outline. * * - `gutter`: This is used to divide components in the page. For example * the header and the lest of the page. * -------------------------------------------------------------------------- */ :root { --vp-c-border: #c2c2c4; --vp-c-divider: #e2e2e3; --vp-c-gutter: #e2e2e3; } .dark { --vp-c-border: #3c3f44; --vp-c-divider: #2e2e32; --vp-c-gutter: #000000; } /** * Colors: Text * * - `text-1`: Used for primary text. * * - `text-2`: Used for muted texts, such as "inactive menu" or "info texts". * * - `text-3`: Used for subtle texts, such as "placeholders" or "caret icon". * -------------------------------------------------------------------------- */ :root { --vp-c-text-1: rgba(60, 60, 67); --vp-c-text-2: rgba(60, 60, 67, 0.78); --vp-c-text-3: rgba(60, 60, 67, 0.56); } .dark { --vp-c-text-1: rgba(255, 255, 245, 0.86); --vp-c-text-2: rgba(235, 235, 245, 0.6); --vp-c-text-3: rgba(235, 235, 245, 0.38); } * { -webkit-tap-highlight-color:rgba(0,0,0,0); } /* 新增align-right类 */ .chat-message.align-right { justify-content: flex-end; margin-left: auto; } .hr-mid-border-content::after{ content: attr(data-content); position: absolute; padding: 4px 1ch; top: 50%; left: 50%; transform: translate(-50%, -50%); color: transparent; border: 1px solid #ff0000; } .hr-solid-content{ color: #000000; border: 0; font-size: 16px; padding: 1em 0; position: relative; } .hr-solid-content::before { content: attr(data-content); position: absolute; padding: 0 1ch; line-height: 1px; border: solid #000000; border-width: 0 19vw; width: fit-content; /* for IE浏览器 */ white-space: nowrap; left: 50%; transform: translateX(-50%); }
2303_806435pww/RW-API-Code_moved
rustedwarfareapicode/.vitepress/theme/style/custom.css
CSS
apache-2.0
5,631
const esbuild = require("esbuild"); const production = process.argv.includes('--production'); const watch = process.argv.includes('--watch'); /** * @type {import('esbuild').Plugin} */ const esbuildProblemMatcherPlugin = { name: 'esbuild-problem-matcher', setup(build) { build.onStart(() => { console.log('[watch] build started'); }); build.onEnd((result) => { result.errors.forEach(({ text, location }) => { console.error(`✘ [ERROR] ${text}`); console.error(` ${location.file}:${location.line}:${location.column}:`); }); console.log('[watch] build finished'); }); }, }; async function main() { const ctx = await esbuild.context({ entryPoints: [ 'src/extension.ts' ], bundle: true, format: 'cjs', minify: production, sourcemap: !production, sourcesContent: false, platform: 'node', outfile: 'dist/extension.js', external: ['vscode'], logLevel: 'silent', plugins: [ /* add to the end of plugins array */ esbuildProblemMatcherPlugin, ], }); if (watch) { await ctx.watch(); } else { await ctx.rebuild(); await ctx.dispose(); } } main().catch(e => { console.error(e); process.exit(1); });
2303_806435pww/RustedWarfareModSupport_moved
esbuild.js
JavaScript
agpl-3.0
1,175
import typescriptEslint from "@typescript-eslint/eslint-plugin"; import tsParser from "@typescript-eslint/parser"; export default [{ files: ["**/*.ts"], }, { plugins: { "@typescript-eslint": typescriptEslint, }, languageOptions: { parser: tsParser, ecmaVersion: 2022, sourceType: "module", }, rules: { "@typescript-eslint/naming-convention": ["warn", { selector: "import", format: ["camelCase", "PascalCase"], }], curly: "warn", eqeqeq: "warn", "no-throw-literal": "warn", semi: "warn", }, }, { files: ["translation/**/*.json"], rules: { // JSON文件不需要分号 semi: "off", } }];
2303_806435pww/RustedWarfareModSupport_moved
eslint.config.mjs
JavaScript
agpl-3.0
749
const fs = require('fs'); const path = require('path'); const translationDir = path.resolve(__dirname, 'translation'); const languages = ['zh-cn', 'en']; // 可根据实际语种扩展 // 进度条显示函数 function showProgressBar(current, total, prefix = '', barLength = 40) { const percentage = total > 0 ? Math.round((current / total) * 100) : 0; const filledBarLength = Math.round((barLength * current) / Math.max(total, 1)); const emptyBarLength = barLength - filledBarLength; const filledBar = '█'.repeat(filledBarLength); const emptyBar = '░'.repeat(emptyBarLength); process.stdout.write(`\r${prefix} [${filledBar}${emptyBar}] ${percentage}% (${current}/${total})`); } function mergeLang(lang) { const langDir = path.join(translationDir, lang); if (!fs.existsSync(langDir)) { console.log(`Language directory ${langDir} does not exist, skipping...`); return; } const files = fs.readdirSync(langDir).filter(f => f.endsWith('.json')); const merged = {}; console.log(`Processing ${files.length} files for language: ${lang}`); let totalKeys = 0; let processedFiles = 0; const totalFiles = files.length; // 显示文件处理进度条 showProgressBar(processedFiles, totalFiles, `Processing files for ${lang}`); for (const file of files) { const filePath = path.join(langDir, file); try { const fileContent = fs.readFileSync(filePath, 'utf8'); // 检查文件是否为空 if (fileContent.trim() === '') { console.log(`\nWarning: File ${filePath} is empty, skipping...`); processedFiles++; showProgressBar(processedFiles, totalFiles, `Processing files for ${lang}`); continue; } const data = JSON.parse(fileContent); const keyCount = Object.keys(data).length; if (keyCount > 0) { Object.assign(merged, data); totalKeys += keyCount; processedFiles++; showProgressBar(processedFiles, totalFiles, `Processing files for ${lang}`); } else { console.log(`\nFile ${filePath} has no keys, skipping...`); processedFiles++; showProgressBar(processedFiles, totalFiles, `Processing files for ${lang}`); } } catch (e) { console.log(`\nError parsing ${filePath}:`, e); processedFiles++; showProgressBar(processedFiles, totalFiles, `Processing files for ${lang}`); } } // 完成后换行 process.stdout.write('\n'); console.log(`Total keys collected for ${lang}: ${totalKeys}`); let outFile; if (lang === 'en') { outFile = path.join(translationDir, `bundle.l10n.json`); } else { outFile = path.join(translationDir, `bundle.l10n.${lang}.json`); } // 显示写入进度 process.stdout.write(`Writing output file for ${lang}... `); // 只有当有内容时才写入文件 if (Object.keys(merged).length > 0) { fs.writeFileSync(outFile, JSON.stringify(merged, null, 2), 'utf8'); process.stdout.write('Done\n'); console.log(`Merged ${lang} translations to ${outFile} with ${Object.keys(merged).length} keys`); } else { process.stdout.write('Skipped (no content)\n'); console.log(`No translations found for ${lang}, not writing output file`); } } // 确保translation目录存在 if (!fs.existsSync(translationDir)) { console.log(`Translation directory ${translationDir} does not exist!`); process.exit(1); } console.log(`Starting merge process for languages: ${languages.join(', ')}`); for (const lang of languages) { console.log(`\nMerging language: ${lang}`); mergeLang(lang); } console.log('\nMerge process completed');
2303_806435pww/RustedWarfareModSupport_moved
merge.js
JavaScript
agpl-3.0
3,647
// 节解析器类 import * as vscode from "vscode"; export class IniSectionSymbolProvider implements vscode.DocumentSymbolProvider { public generateSectionData(name: string): string { // 处理不同类型的节 let baseName = name; // 处理带下划线的节名称,如 turret_NAME, projectile_NAME 等 if (name.includes("_")) { baseName = name.substring(0, name.indexOf("_")); } // 特殊处理 leg_ 和 arm_ 类型 if (name.startsWith("leg_")) { baseName = "leg"; } else if (name.startsWith("arm_")) { baseName = "arm"; } // 特殊处理 spawnUnits:LIST 和 spawnProjectiles:LIST 类型 if (name.startsWith("spawnUnits:")) { baseName = "spawnUnits"; } else if (name.startsWith("spawnProjectiles:")) { baseName = "spawnProjectiles"; } // 特殊处理 Prices/Resources 类型 if (name === "Prices/Resources") { baseName = "prices"; } return vscode.l10n.t(`data.sections.${baseName}`); } public provideDocumentSymbols( document: vscode.TextDocument, token: vscode.CancellationToken ): Promise<vscode.DocumentSymbol[]> { return new Promise((resolve, reject) => { const symbols: vscode.DocumentSymbol[] = []; let sectionStart: vscode.Position | null = null; let sectionName: string | null = null; for (let i = 0; i < document.lineCount; i++) { const line = document.lineAt(i); const lineText = line.text.trim(); // 判断是否为节的开始 - 以 [ 开头,以 ] 结尾 if (lineText.startsWith("[") && lineText.endsWith("]")) { // 如果之前已经有一个节,那么结束它 if (sectionStart !== null && sectionName !== null) { const sectionEnd = new vscode.Position(i - 1, document.lineAt(i - 1).text.length); const sectionRange = new vscode.Range(sectionStart, sectionEnd); const sectionSymbol = new vscode.DocumentSymbol( sectionName, this.generateSectionData(sectionName), vscode.SymbolKind.Module, sectionRange, new vscode.Range(sectionStart, sectionStart) ); symbols.push(sectionSymbol); } // 开始新的节 sectionStart = line.range.start; sectionName = lineText.substring(1, lineText.length - 1); } } // 处理最后一个节(如果文件以节结尾) if (sectionStart !== null && sectionName !== null) { const lastLine = document.lineAt(document.lineCount - 1); const sectionEnd = new vscode.Position(lastLine.lineNumber, lastLine.text.length); const sectionRange = new vscode.Range(sectionStart, sectionEnd); const sectionSymbol = new vscode.DocumentSymbol( sectionName, this.generateSectionData(sectionName), vscode.SymbolKind.Module, sectionRange, new vscode.Range(sectionStart, sectionStart) ); symbols.push(sectionSymbol); } resolve(symbols); }); } } // This method is called when your extension is deactivated export function deactivate() {}
2303_806435pww/RustedWarfareModSupport_moved
src/Section.ts
TypeScript
agpl-3.0
3,215
export const _debugConfig = {};
2303_806435pww/RustedWarfareModSupport_moved
src/_config.ts
TypeScript
agpl-3.0
32
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; // 定义类型颜色映射接口 interface TypeColorMap { [key: string]: string; } /** * 着色器管理器类 * 负责加载和管理不同属性类型的着色信息 */ export class ColorizerManager { private typeColors: TypeColorMap; private decorators: Map<string, vscode.TextEditorDecorationType>; constructor() { this.typeColors = this.loadTypeColors(); this.decorators = new Map(); this.initializeDecorators(); } /** * 从type.json加载类型颜色映射 * @returns 类型颜色映射对象 */ private loadTypeColors(): TypeColorMap { try { const typePath = path.join(__dirname, '..', 'data', 'type.json'); const typeData = JSON.parse(fs.readFileSync(typePath, 'utf8')); const colorMap: TypeColorMap = {}; for (const type of typeData) { colorMap[type.name] = type.color; } return colorMap; } catch (error) { console.error('Error loading type colors:', error); // 返回默认颜色映射 return { 'string': '#FF6B6B', 'int': '#4ECDC4', 'float': '#45B7D1', 'bool': '#96CEB4', 'string(s)': '#FFEAA7', 'int(s)': '#DDA0DD' }; } } /** * 初始化装饰器 */ private initializeDecorators() { // 为每种类型创建装饰器 for (const [typeName, color] of Object.entries(this.typeColors)) { const decorator = vscode.window.createTextEditorDecorationType({ color: color, overviewRulerColor: color, overviewRulerLane: vscode.OverviewRulerLane.Right }); this.decorators.set(typeName, decorator); } } /** * 获取指定类型的装饰器 * @param typeName 类型名称 * @returns 装饰器类型对象,如果未找到则返回undefined */ public getDecorator(typeName: string): vscode.TextEditorDecorationType | undefined { return this.decorators.get(typeName); } /** * 获取所有类型颜色映射 * @returns 类型颜色映射对象 */ public getTypeColors(): TypeColorMap { return { ...this.typeColors }; } /** * 清理所有装饰器资源 */ public dispose() { // 清理所有装饰器 for (const decorator of this.decorators.values()) { decorator.dispose(); } this.decorators.clear(); } } // 创建全局着色器管理器实例 let colorizerManager: ColorizerManager | null = null; /** * 获取全局着色器管理器实例 * @returns 着色器管理器实例 */ export function getColorizerManager(): ColorizerManager { if (!colorizerManager) { colorizerManager = new ColorizerManager(); } return colorizerManager; } /** * 销毁全局着色器管理器实例 */ export function disposeColorizerManager() { if (colorizerManager) { colorizerManager.dispose(); colorizerManager = null; } }
2303_806435pww/RustedWarfareModSupport_moved
src/colorizer.ts
TypeScript
agpl-3.0
3,279
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import { extractExampleValue, getSectionProperties, isInsideSection, isAtValidLineStart, hasColonInLine } from './dataProcessor'; /** * 为补全项生成格式化的文档信息 * @param property 属性对象 * @returns 格式化的Markdown文档字符串 */ function generateCompletionDocumentation(property: any): vscode.MarkdownString { const doc = new vscode.MarkdownString(); // 先翻译各字段 const nameLabel = vscode.l10n.t('completionprovider.name'); const typeLabel = vscode.l10n.t('completionprovider.type'); const versionLabel = vscode.l10n.t('completionprovider.version'); const descriptionLabel = vscode.l10n.t('completionprovider.description'); const isOutdatedLabel = vscode.l10n.t('completionprovider.isOutdated'); const exampleLabel = vscode.l10n.t('completionprovider.example'); const nameValue = vscode.l10n.t(property.name); const typeValue = property.type; const versionValue = property.version ? vscode.l10n.t(property.version) : ''; const descriptionValue = property.description ? vscode.l10n.t(property.description) : ''; const exampleValue = property.example ? vscode.l10n.t(property.example) : ''; // 添加名称字段 doc.appendMarkdown(`**${nameLabel}:** ${nameValue}\n\n`); // 添加类型字段 doc.appendMarkdown(`**${typeLabel}:** \`${typeValue}\`\n\n`); // 添加版本字段 if (property.version) { doc.appendMarkdown(`**${versionLabel}:** ${versionValue}\n\n`); } // 添加描述字段 if (property.description) { doc.appendMarkdown(`**${descriptionLabel}:** ${descriptionValue}\n\n`); } // 添加过时标记 if (property.isOutdated) { doc.appendMarkdown(`⚠️ **${isOutdatedLabel}:** true\n\n`); } // 添加示例字段 if (property.example) { doc.appendMarkdown(`**${exampleLabel}:**\n\`\`\`ini\n${exampleValue}\n\`\`\``); } return doc; } /** * 创建补全项数组 * @param sectionName 节名称 * @param properties 属性数组 * @returns 补全项数组 */ function createCompletionItems(sectionName: string, properties: any[]): vscode.CompletionItem[] { return properties.map(property => { const item = new vscode.CompletionItem( property.name, vscode.CompletionItemKind.Property ); // 设置补全项的详细信息和文档 item.detail = property.type ? `${property.type} - ${property.version || ''}`.trim() : property.version || ''; item.documentation = generateCompletionDocumentation(property); // 设置插入文本格式 const exampleValue = property.example ? extractExampleValue(property.example) : ''; item.insertText = new vscode.SnippetString(`${property.name}: \${1:${exampleValue}}`); return item; }); } /** * 创建节名称补全项数组 * @returns 补全项数组 */ function createSectionCompletionItems(): vscode.CompletionItem[] { try { // 读取节数据 const sectionsPath = path.join(__dirname, '..', 'data', 'sections.json'); const sectionsData = JSON.parse(fs.readFileSync(sectionsPath, 'utf8')); // 为每个节创建补全项 return sectionsData.data.map((section: any) => { const item = new vscode.CompletionItem( section.name, vscode.CompletionItemKind.Module ); // 设置文档信息 item.documentation = new vscode.MarkdownString( `**${vscode.l10n.t('completionprovider.description')}:** ${vscode.l10n.t(section.description)}` ); // 设置插入文本,包含中括号 item.insertText = new vscode.SnippetString(`${section.name}`); // 设置排序优先级 item.sortText = '0'; return item; }); } catch (error) { console.error('Error reading sections.json:', error); return []; } } /** * 节名称补全提供者类 */ export class SectionNameCompletionProvider implements vscode.CompletionItemProvider { provideCompletionItems( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { // 获取光标所在行的文本 const lineText = document.lineAt(position.line).text; // 获取光标前的文本 const textBeforeCursor = lineText.substring(0, position.character); // 检查光标前是否有[但没有匹配的] const lastOpenBracketIndex = textBeforeCursor.lastIndexOf('['); const lastCloseBracketIndex = textBeforeCursor.lastIndexOf(']'); // 如果有未闭合的[(即存在[且它在最近的]之后),则提供节名称补全 if (lastOpenBracketIndex !== -1 && lastOpenBracketIndex > lastCloseBracketIndex) { return createSectionCompletionItems(); } return []; } } /** * 通用的节补全提供者类 */ export class GenericCompletionProvider implements vscode.CompletionItemProvider { private sectionName: string; private sectionMatcher: (sectionName: string) => boolean; constructor(sectionName: string, sectionMatcher?: (sectionName: string) => boolean) { this.sectionName = sectionName; this.sectionMatcher = sectionMatcher || ((name: string) => name === sectionName); } provideCompletionItems( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { // 如果不在目标节内,返回空数组 if (!isInsideSection(document, position, this.sectionMatcher)) { return []; } // 检查是否在有效的行首位置(允许输入属性名) if (!isAtValidLineStart(document, position)) { return []; } // 如果行中已经包含冒号,则不提供属性补全(为值补全保留空间) if (hasColonInLine(document, position)) { return []; } // 获取属性并创建补全项 const properties = getSectionProperties(this.sectionName); return createCompletionItems(this.sectionName, properties); } } // 特定节的补全提供者类 export class CoreCompletionProvider extends GenericCompletionProvider { constructor() { super('core', (name: string) => name === 'core'); } } export class CanBuildCompletionProvider extends GenericCompletionProvider { constructor() { super('canBuild', (name: string) => /^canBuild_\p{L}+$/u.test(name)); } } export class GraphicsCompletionProvider extends GenericCompletionProvider { constructor() { super('graphics', (name: string) => name === 'graphics'); } } export class AttackCompletionProvider extends GenericCompletionProvider { constructor() { super('attack', (name: string) => name === 'attack'); } } export class TurretCompletionProvider extends GenericCompletionProvider { constructor() { super('turret', (name: string) => /^turret_\p{L}+$/u.test(name)); } } export class ProjectileCompletionProvider extends GenericCompletionProvider { constructor() { super('projectile', (name: string) => /^projectile_\p{L}+$/u.test(name)); } } export class MovementCompletionProvider extends GenericCompletionProvider { constructor() { super('movement', (name: string) => name === 'movement'); } } export class AiCompletionProvider extends GenericCompletionProvider { constructor() { super('ai', (name: string) => name === 'ai'); } } export class LegArmCompletionProvider extends GenericCompletionProvider { constructor() { super('leg_arm', (sectionName: string) => /^leg_\p{L}+$/u.test(sectionName) || /^arm_\p{L}+$/u.test(sectionName)); } } export class AttachmentCompletionProvider extends GenericCompletionProvider { constructor() { super('attachment', (name: string) => /^attachment_\p{L}+$/u.test(name)); } } export class ActionCompletionProvider extends GenericCompletionProvider { constructor() { super('action', (name: string) => /^(action_|hiddenAction_)\p{L}+$/u.test(name)); } } export class EffectCompletionProvider extends GenericCompletionProvider { constructor() { super('effect', (name: string) => /^effect_\p{L}+$/u.test(name)); } } export class AnimationCompletionProvider extends GenericCompletionProvider { constructor() { super('animation', (name: string) => /^animation_\p{L}+$/u.test(name)); } } export class ModInfoCompletionProvider extends GenericCompletionProvider { constructor() { super('mod-info', (name: string) => name === 'mod' || name === 'music'); } } export class GlobalResourceCompletionProvider extends GenericCompletionProvider { constructor() { super('global_resource', (name: string) => /^global_resource_\p{L}+$/u.test(name)); } } export class ResourceCompletionProvider extends GenericCompletionProvider { constructor() { super('resource', (name: string) => /^resource_\p{L}+$/u.test(name)); } } // 新增的补全提供者类 export class DecalCompletionProvider extends GenericCompletionProvider { constructor() { super('decal', (name: string) => /^decal_\p{L}+$/u.test(name)); } } export class PlacementRuleCompletionProvider extends GenericCompletionProvider { constructor() { super('placementRule', (name: string) => /^placementRule_\p{L}+$/u.test(name)); } }
2303_806435pww/RustedWarfareModSupport_moved
src/completionProvider.ts
TypeScript
agpl-3.0
10,053
import * as fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; /** * 从示例字符串中提取值部分 * @param example 示例字符串 * @returns 提取的值 */ export function extractExampleValue(example: string): string { return example.split(':')[1]?.trim() || ''; } /** * 获取节的基本名称(去除下划线后缀等) * @param name 节名称 * @returns 基本节名称 */ export function getBaseSectionName(name: string): string { let baseName = name; // 特殊处理 leg_ 和 arm_ 类型 if (name.startsWith("leg_")) { baseName = "leg"; } else if (name.startsWith("arm_")) { baseName = "arm"; } // 特殊处理 spawnUnits:LIST 和 spawnProjectiles:LIST 类型 if (name.startsWith("spawnUnits:")) { baseName = "spawnUnits"; } else if (name.startsWith("spawnProjectiles:")) { baseName = "spawnProjectiles"; } // 特殊处理 action_ 和 hiddenAction_ 类型 if (name.startsWith("action_") || name.startsWith("hiddenAction_")) { baseName = "action"; } // 特殊处理 Prices/Resources 类型 if (name === "Prices/Resources") { baseName = "prices"; } if (name.startsWith('global_resource')) { baseName = 'global_resource'; } if (name.startsWith('canBuild')) { baseName = 'canBuild'; } return baseName; } /** * 获取节的属性数据 * @param sectionName 节名称 * @returns 属性数组 */ export function getSectionProperties(sectionName: string): any[] { try { // 获取基本节名称 const baseSectionName = getBaseSectionName(sectionName); // 构建语言特定的数据文件路径 let sectionPath = path.join(__dirname, '..', 'data', 'sections', `${baseSectionName}.json`); // 检查是否存在语言特定的文件 const localizedPath = path.join(__dirname, '..', 'data', 'sections', vscode.env.language, `${baseSectionName}.json`); if (fs.existsSync(localizedPath)) { sectionPath = localizedPath; } const sectionData = JSON.parse(fs.readFileSync(sectionPath, 'utf8')); return sectionData.data || []; } catch (error) { console.error(`Error reading ${sectionName}.json:`, error); return []; } } /** * 创建一个简单的节匹配器函数 * @param sectionName 节名称 * @returns 匹配器函数 */ export function createSimpleSectionMatcher(sectionName: string): (name: string) => boolean { return (name: string) => name === sectionName; } /** * 创建一个前缀匹配器函数 * @param prefix 前缀 * @returns 匹配器函数 */ export function createPrefixSectionMatcher(prefix: string): (name: string) => boolean { return (name: string) => name.startsWith(prefix); } /** * 创建一个正则表达式匹配器函数 * @param pattern 正则表达式模式 * @returns 匹配器函数 */ export function createRegexSectionMatcher(pattern: RegExp): (name: string) => boolean { return (name: string) => pattern.test(name); } /** * 检查当前位置是否在指定节内 * @param document 文档对象 * @param position 位置对象 * @param sectionMatcher 节匹配器函数 * @returns 是否在节内 */ export function isInsideSection(document: vscode.TextDocument, position: vscode.Position, sectionMatcher: (sectionName: string) => boolean): boolean { // 从光标所在行向上遍历,查找最近的节定义 let stop = false; for (let i = position.line - 1; i >= 0; i--) { const line = document.lineAt(i).text.trim(); //弱匹配,因为只有节存在[]符号 if (line.startsWith('[') && line.endsWith(']')) { const sectionName = line.substring(1, line.length - 1); stop = true; return sectionMatcher(sectionName); } if(stop) break; } // // 特殊处理 mod-info.txt 文件 // // 如果文件名是 mod-info.txt,则检查是否在文件开头(没有节的情况下) // if (document.fileName.endsWith('mod-info.txt')) { // // 检查是否在文件的前几行且没有遇到任何节 // let hasSection = false; // for (let i = 0; i < Math.min(position.line, 10); i++) { // const line = document.lineAt(i).text.trim(); // if (line.startsWith('[') && line.endsWith(']')) { // hasSection = true; // break; // } // } // // 如果没有节且在文件开头附近,则认为是在mod-info节中 // if (!hasSection && position.line < 10) { // // 直接检查是否匹配mod或music节 // return sectionMatcher('mod') || sectionMatcher('music'); // } // } return false; } /** * 检查光标是否在行首(行首允许有空格或制表符,以及属性名字符) * 修复:在输入过程中,光标前可能有已输入的字符,需要检查这些字符是否构成属性名的一部分 * @param document 文档对象 * @param position 位置对象 * @returns 是否在有效行首位置 */ export function isAtValidLineStart(document: vscode.TextDocument, position: vscode.Position): boolean { const line = document.lineAt(position.line).text; const beforeCursor = line.substring(0, position.character); // 允许行首有空格或制表符 // 允许有属性名字符(字母、数字、下划线) // 不允许有冒号等其他字符 return /^[ \t]*[a-zA-Z0-9_]*$/.test(beforeCursor); } /** * 检查行中是否已经包含冒号 * @param document 文档对象 * @param position 位置对象 * @returns 行中是否已包含冒号 */ export function hasColonInLine(document: vscode.TextDocument, position: vscode.Position): boolean { const line = document.lineAt(position.line).text; const beforeCursor = line.substring(0, position.character); return beforeCursor.includes(':'); }
2303_806435pww/RustedWarfareModSupport_moved
src/dataProcessor.ts
TypeScript
agpl-3.0
6,065
import * as vscode from 'vscode'; import { getSectionProperties } from './dataProcessor'; import { getColorizerManager, disposeColorizerManager } from './colorizer'; // 节属性装饰器类 export class SectionPropertyDecorator { private disposable: vscode.Disposable; constructor() { // 订阅文本编辑器更改事件 const disposables: vscode.Disposable[] = []; // 订阅活动文本编辑器更改事件 disposables.push( vscode.window.onDidChangeActiveTextEditor(editor => { if (editor) { this.updateDecorations(editor); } }) ); // 订阅文档更改事件 disposables.push( vscode.workspace.onDidChangeTextDocument(event => { const editor = vscode.window.activeTextEditor; if (editor && event.document === editor.document) { this.updateDecorations(editor); } }) ); // 订阅选择更改事件 disposables.push( vscode.window.onDidChangeTextEditorSelection(event => { this.updateDecorations(event.textEditor); }) ); this.disposable = vscode.Disposable.from(...disposables); // 立即更新当前编辑器的装饰 if (vscode.window.activeTextEditor) { this.updateDecorations(vscode.window.activeTextEditor); } } public dispose() { this.disposable.dispose(); disposeColorizerManager(); } private updateDecorations(editor: vscode.TextEditor) { const colorizerManager = getColorizerManager(); const document = editor.document; if (document.languageId !== 'ini') { return; } // 存储每种类型的装饰范围 const decorations = new Map<string, vscode.Range[]>(); // 获取文档中的所有节 const sections = this.parseSections(document); // 为每个节获取属性并应用装饰 for (const section of sections) { const properties = getSectionProperties(section.name); if (properties.length === 0) continue; // 创建属性名称到类型的映射 const propertyTypeMap = new Map<string, string>(); for (const prop of properties) { propertyTypeMap.set(prop.name, prop.type); } // 遍历节内的行 for (let i = section.startLine + 1; i < section.endLine; i++) { if (i >= document.lineCount) break; const line = document.lineAt(i); const text = line.text; // 检查是否是属性行(包含冒号) const colonIndex = text.indexOf(':'); if (colonIndex > 0) { // 提取属性名称 const propertyName = text.substring(0, colonIndex).trim(); const propertyType = propertyTypeMap.get(propertyName); if (propertyType) { // 创建装饰范围(装饰属性名称) const nameRange = new vscode.Range( new vscode.Position(i, colonIndex - propertyName.length), new vscode.Position(i, colonIndex) ); // 添加到对应的装饰类型中 if (!decorations.has(propertyType)) { decorations.set(propertyType, []); } decorations.get(propertyType)?.push(nameRange); // 创建装饰范围(装饰属性值) const valueStart = colonIndex + 1; const lineEnd = line.text.length; if (valueStart < lineEnd) { // 确保有值 const valueRange = new vscode.Range( new vscode.Position(i, valueStart), new vscode.Position(i, lineEnd) ); // 添加到对应的装饰类型中 if (!decorations.has(propertyType)) { decorations.set(propertyType, []); } decorations.get(propertyType)?.push(valueRange); } } } } } // 应用装饰 for (const [typeName, ranges] of decorations.entries()) { const decorator = colorizerManager.getDecorator(typeName); if (decorator) { editor.setDecorations(decorator, ranges); } } } private parseSections(document: vscode.TextDocument): Array<{name: string, startLine: number, endLine: number}> { const sections: Array<{name: string, startLine: number, endLine: number}> = []; let currentSection: {name: string, startLine: number} | null = null; for (let i = 0; i < document.lineCount; i++) { const line = document.lineAt(i); const text = line.text.trim(); // 检查是否是节开始 if (text.startsWith('[') && text.endsWith(']')) { // 如果已经有节在进行中,结束它 if (currentSection) { sections.push({ name: currentSection.name, startLine: currentSection.startLine, endLine: i }); } // 开始新节 const sectionName = text.substring(1, text.length - 1); currentSection = { name: sectionName, startLine: i }; } } // 结束最后一个节 if (currentSection) { sections.push({ name: currentSection.name, startLine: currentSection.startLine, endLine: document.lineCount }); } return sections; } }
2303_806435pww/RustedWarfareModSupport_moved
src/decorator.ts
TypeScript
agpl-3.0
6,549
// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; import { IniSectionSymbolProvider } from './Section'; import { CoreCompletionProvider, CanBuildCompletionProvider, GraphicsCompletionProvider, AttackCompletionProvider, TurretCompletionProvider, ProjectileCompletionProvider, MovementCompletionProvider, AiCompletionProvider, LegArmCompletionProvider, AttachmentCompletionProvider, ActionCompletionProvider, EffectCompletionProvider, AnimationCompletionProvider, SectionNameCompletionProvider, GlobalResourceCompletionProvider, ResourceCompletionProvider, DecalCompletionProvider, PlacementRuleCompletionProvider } from './completionProvider'; import { ValueCompletionProvider } from './valueComple/valueCompletionProvider'; import { SectionPropertyDecorator } from './decorator'; import { RustedWarfareHoverProvider } from './hoverProvider'; // This method is called when your extension is activated // Your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log(vscode.l10n.t('Congratulations, your extension "rustedwarfaremodsupport" is now active!')); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json const disposable = vscode.commands.registerCommand('rustedwarfaremodsupport.helloWorld', () => { // The code you place here will be executed every time your command is executed // Display a message box to the user vscode.window.showInformationMessage(vscode.l10n.t('Hello World from RustedWarfareModSupport!')); }); // 注册文档解析器,用于识别节 const sectionParser = vscode.languages.registerDocumentSymbolProvider( { language: 'ini' }, new IniSectionSymbolProvider() ); // 创建所有补全提供者的数组 const completionProviders = [ new CoreCompletionProvider(), new CanBuildCompletionProvider(), new GraphicsCompletionProvider(), new AttackCompletionProvider(), new TurretCompletionProvider(), new ProjectileCompletionProvider(), new MovementCompletionProvider(), new AiCompletionProvider(), new LegArmCompletionProvider(), new AttachmentCompletionProvider(), new ActionCompletionProvider(), new EffectCompletionProvider(), new AnimationCompletionProvider(), new GlobalResourceCompletionProvider(), new ResourceCompletionProvider(), new DecalCompletionProvider(), new PlacementRuleCompletionProvider() ]; // 注册所有补全提供者(不设置触发字符,使用默认触发机制) const completionSubscriptions = completionProviders.map(provider => vscode.languages.registerCompletionItemProvider( { language: 'ini' }, provider ) ); // 注册值补全提供者 const valueCompletionProvider = new ValueCompletionProvider(); const valueCompletionSubscription = vscode.languages.registerCompletionItemProvider( { language: 'ini' }, valueCompletionProvider, ':', ' ', ',' // 在冒号、空格和逗号后触发值补全 ); // 注册节名称补全提供者,在多种字符输入时都可触发 const sectionNameCompletionProvider = new SectionNameCompletionProvider(); const sectionNameCompletionSubscription = vscode.languages.registerCompletionItemProvider( { language: 'ini' }, sectionNameCompletionProvider, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ); // 注册悬停提供者 const hoverProvider = vscode.languages.registerHoverProvider( { language: 'ini' }, new RustedWarfareHoverProvider() ); // 注册装饰器 const decorator = new SectionPropertyDecorator(); context.subscriptions.push(decorator); context.subscriptions.push(disposable); context.subscriptions.push(sectionParser); context.subscriptions.push(valueCompletionSubscription); context.subscriptions.push(sectionNameCompletionSubscription); context.subscriptions.push(hoverProvider); completionSubscriptions.forEach(subscription => context.subscriptions.push(subscription)); } // This method is called when your extension is deactivated export function deactivate() {}
2303_806435pww/RustedWarfareModSupport_moved
src/extension.ts
TypeScript
agpl-3.0
4,721
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import { getSectionProperties } from './dataProcessor'; /** * RustedWarfare配置文件的悬停提供者 * 当用户将鼠标悬停在属性或值上时,显示详细信息 */ export class RustedWarfareHoverProvider implements vscode.HoverProvider { /** * 当用户将鼠标悬停在文档上时调用 * @param document 当前文档 * @param position 鼠标位置 * @param token 取消令牌 * @returns 悬停信息或Promise */ public provideHover( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken ): vscode.ProviderResult<vscode.Hover> { // 获取当前行文本 const line = document.lineAt(position.line); const lineText = line.text; // 检查是否在节内 const currentSection = this.getCurrentSection(document, position); if (!currentSection) { return null; } // 获取节属性 const properties = getSectionProperties(currentSection); if (properties.length === 0) { console.log('No properties found for section'); return null; } // 创建属性名称到属性对象的映射 const propertyMap = new Map<string, any>(); for (const prop of properties) { propertyMap.set(prop.name, prop); } // 检查悬停位置是否在属性名上 const hoverOnPropertyName = this.checkHoverOnPropertyName(lineText, position.character, propertyMap); if (hoverOnPropertyName) { console.log(`Hover on property name: ${hoverOnPropertyName.property.name}`); return this.createPropertyHover(hoverOnPropertyName.property); } // 检查悬停位置是否在属性值上 const hoverOnPropertyValue = this.checkHoverOnPropertyValue(lineText, position.character, propertyMap); if (hoverOnPropertyValue) { console.log(`Hover on property value. Property: ${hoverOnPropertyValue.property.name}, Word: ${hoverOnPropertyValue.word}`); return this.createPropertyValueHover(hoverOnPropertyValue.property, hoverOnPropertyValue.valuePart, hoverOnPropertyValue.word, 0); } console.log('No hover match found'); return null; } /** * 获取当前所在的节名称 * @param document 文档对象 * @param position 位置对象 * @returns 节名称,如果未找到则返回null */ private getCurrentSection(document: vscode.TextDocument, position: vscode.Position): string | null { // 从当前位置向上搜索,找到最近的节定义 for (let i = position.line; i >= 0; i--) { const line = document.lineAt(i).text.trim(); if (line.startsWith('[') && line.endsWith(']')) { return line.substring(1, line.length - 1); } } return null; } /** * 检查悬停是否在属性名上 * @param lineText 行文本 * @param characterPosition 字符位置 * @param propertyMap 属性映射 * @returns 属性对象,如果未找到则返回null */ private checkHoverOnPropertyName( lineText: string, characterPosition: number, propertyMap: Map<string, any> ): { property: any } | null { // 查找冒号位置 const colonIndex = lineText.indexOf(':'); if (colonIndex <= 0) { return null; } // 检查光标是否在冒号之前(属性名部分) if (characterPosition >= colonIndex) { return null; } // 提取属性名 const propertyName = lineText.substring(0, colonIndex).trim(); // 查找匹配的属性 const property = propertyMap.get(propertyName); if (property) { return { property }; } return null; } /** * 检查悬停是否在属性值上 * @param lineText 行文本 * @param characterPosition 字符位置 * @param propertyMap 属性映射 * @returns 属性对象和值部分信息,如果未找到则返回null */ private checkHoverOnPropertyValue( lineText: string, characterPosition: number, propertyMap: Map<string, any> ): { property: any, valuePart: string, word: string } | null { // 查找冒号位置 const colonIndex = lineText.indexOf(':'); if (colonIndex < 0) { return null; } // 检查光标是否在冒号之后(属性值部分) if (characterPosition <= colonIndex) { return null; } // 提取属性名 const propertyName = lineText.substring(0, colonIndex).trim(); // 查找匹配的属性 const property = propertyMap.get(propertyName); if (property) { // 获取值部分 const valuePart = lineText.substring(colonIndex + 1).trim(); const word = this.getWordAtPosition(lineText, characterPosition); return { property, valuePart, word }; } return null; } /** * 创建属性悬停信息 * @param property 属性对象 * @returns 悬停信息 */ private createPropertyHover(property: any): vscode.Hover { // 创建悬停内容 const hoverContent = new vscode.MarkdownString(); // 先翻译各字段 const nameLabel = vscode.l10n.t('completionprovider.name'); const typeLabel = vscode.l10n.t('completionprovider.type'); const versionLabel = vscode.l10n.t('completionprovider.version'); const descriptionLabel = vscode.l10n.t('completionprovider.description'); const isOutdatedLabel = vscode.l10n.t('completionprovider.isOutdated'); const exampleLabel = vscode.l10n.t('completionprovider.example'); const nameValue = vscode.l10n.t(property.name); const typeValue = property.type; const versionValue = property.version ? vscode.l10n.t(property.version) : ''; const descriptionValue = property.description ? vscode.l10n.t(property.description) : ''; const exampleValue = property.example ? vscode.l10n.t(property.example) : ''; // 添加名称字段 hoverContent.appendMarkdown(`**${nameLabel}:** ${nameValue}\n\n`); // 添加类型字段 hoverContent.appendMarkdown(`**${typeLabel}:** \`${typeValue}\`\n\n`); // 添加版本字段 if (property.version) { hoverContent.appendMarkdown(`**${versionLabel}:** ${versionValue}\n\n`); } // 添加描述字段 if (property.description) { hoverContent.appendMarkdown(`**${descriptionLabel}:** ${descriptionValue}\n\n`); } // 添加过时标记 if (property.isOutdated) { hoverContent.appendMarkdown(`⚠️ **${isOutdatedLabel}:** true\n\n`); } // 添加示例字段 if (property.example) { hoverContent.appendMarkdown(`**${exampleLabel}:**\n\`\`\`ini\n${exampleValue}\n\`\`\``); } return new vscode.Hover(hoverContent); } /** * 获取指定位置的单词 * @param text 文本 * @param position 位置 * @returns 单词 */ private getWordAtPosition(text: string, position: number): string { if (position < 0 || position > text.length) { return ''; } // 以空格等为分隔符查找单词 const leftPart = text.substring(0, position); const rightPart = text.substring(position); // 查找左侧边界 const leftMatch = leftPart.match(/[^\s(),]*$/); const leftWord = leftMatch ? leftMatch[0] : ''; // 查找右侧边界 const rightMatch = rightPart.match(/^[^\s(),]*/); const rightWord = rightMatch ? rightMatch[0] : ''; const word = leftWord + rightWord; // 检查是否是self.xxx格式的方法调用 // 如果当前单词是点号右侧的部分,且点号左侧是self,则组合成self.xxx if (leftWord.endsWith('.') && leftWord.length > 1) { const beforeDot = leftWord.substring(0, leftWord.length - 1); if (beforeDot === 'self') { const result = beforeDot + '.' + rightWord; return result; } } // 如果当前单词是self,且点号右侧有内容,则组合成self.xxx if (leftWord === 'self' && rightPart.startsWith('.')) { const rightPartAfterDot = rightPart.substring(1); const rightWordMatch = rightPartAfterDot.match(/^[^\s(),]*/); const rightWordAfterDot = rightWordMatch ? rightWordMatch[0] : ''; if (rightWordAfterDot) { const result = leftWord + '.' + rightWordAfterDot; return result; } } return word; } /** * 创建属性值悬停信息 * @param property 属性对象 * @param valuePart 值部分文本 * @param word 光标下的单词 * @param positionInValue 坐标在值中的位置 * @returns 悬停信息 */ private createPropertyValueHover( property: any, valuePart: string, word: string, positionInValue: number ): vscode.Hover | null { // 根据属性类型提供相应的值信息 switch (property.type) { case 'bool': return this.createBooleanValueHover(word); case 'LogicBoolean': return this.createLogicBooleanValueHover(word, valuePart, positionInValue); case 'string': case 'int': case 'float': case 'string(s)': case 'int(s)': case 'float / s': // 对于基本类型,显示属性信息 return this.createPropertyHover(property); default: // 对于其他类型,也显示属性信息 return this.createPropertyHover(property); } } /** * 创建LogicBoolean值悬停信息 * @param word 单词 * @param valuePart 值部分文本 * @param positionInValue 坐标在值中的位置 * @returns 悬停信息 */ private createLogicBooleanValueHover( word: string, valuePart: string, positionInValue: number ): vscode.Hover | null { const trimmedWord = word.trim(); if (!trimmedWord) { return null; } // 检查是否为LogicBoolean关键字 if (trimmedWord === 'true' || trimmedWord === 'false' || trimmedWord === 'if' || trimmedWord === 'and' || trimmedWord === 'or' || trimmedWord === 'not') { return this.createLogicBooleanKeywordHover(trimmedWord); } // 检查是否为self.开头的方法 if (trimmedWord.startsWith('self.')) { return this.createLogicBooleanSelfMethodHover(trimmedWord); } // 检查是否为其他LogicBoolean函数 return this.createLogicBooleanFunctionHover(trimmedWord); } /** * 创建LogicBoolean关键字悬停信息 * @param keyword 关键字 * @returns 悬停信息 */ private createLogicBooleanKeywordHover(keyword: string): vscode.Hover | null { const hoverContent = new vscode.MarkdownString(); switch (keyword) { case 'true': hoverContent.appendMarkdown(`**${vscode.l10n.t('valuecompletionprovider.bool.detail')}**\n\n`); hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.logicboolean.true.description')); break; case 'false': hoverContent.appendMarkdown(`**${vscode.l10n.t('valuecompletionprovider.bool.detail')}**\n\n`); hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.logicboolean.false.description')); break; case 'if': hoverContent.appendMarkdown(`**LogicBoolean Keyword**\n\n`); hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.logicboolean.if.description')); break; case 'and': hoverContent.appendMarkdown(`**LogicBoolean Connector**\n\n`); hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.logicboolean.and.description')); break; case 'or': hoverContent.appendMarkdown(`**LogicBoolean Connector**\n\n`); hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.logicboolean.or.description')); break; case 'not': hoverContent.appendMarkdown(`**LogicBoolean Conditional**\n\n`); hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.logicboolean.not.description')); break; default: return null; } return new vscode.Hover(hoverContent); } /** * 创建LogicBoolean self方法悬停信息 * @param method 方法名 * @returns 悬停信息 */ private createLogicBooleanSelfMethodHover(method: string): vscode.Hover | null { // 从logicboolean.json加载数据 try { const valuePath = path.join(__dirname, '..', 'data', 'value', 'logicboolean.json'); const valueData = JSON.parse(fs.readFileSync(valuePath, 'utf8')); // 查找匹配的方法 const methodPart = method.substring(5); // 移除"self."前缀 const methodBase = methodPart.split('(')[0]; // 获取方法名,忽略参数部分 console.log(`Searching for method: self.${methodBase} or starting with self.${methodBase}.`); for (const item of valueData.data) { if (item.name === `self.${methodBase}` || item.name.startsWith(`self.${methodBase}.`) || item.name === `self.${methodBase}()`) { console.log(`Found matching method: ${item.name}`); const hoverContent = new vscode.MarkdownString(); hoverContent.appendMarkdown(`**LogicBoolean Function**\n\n`); hoverContent.appendMarkdown(`${vscode.l10n.t(item.description)}\n\n`); if (item.version) { hoverContent.appendMarkdown(`*Version: ${item.version}*\n\n`); } if (item.example) { hoverContent.appendMarkdown(`\`\`\`ini\n${vscode.l10n.t(item.example)}\n\`\`\``); } return new vscode.Hover(hoverContent); } } console.log(`No matching method found for: ${method}`); } catch (error) { console.error('Error reading logicboolean.json:', error); } return null; } /** * 创建LogicBoolean函数悬停信息 * @param func 函数名 * @returns 悬停信息 */ private createLogicBooleanFunctionHover(func: string): vscode.Hover | null { // 从logicboolean.json加载数据 try { const valuePath = path.join(__dirname, '..', 'data', 'value', 'logicboolean.json'); const valueData = JSON.parse(fs.readFileSync(valuePath, 'utf8')); // 查找匹配的函数 const funcBase = func.split('(')[0]; // 获取函数名,忽略参数部分 for (const item of valueData.data) { if (item.name === funcBase) { const hoverContent = new vscode.MarkdownString(); hoverContent.appendMarkdown(`**LogicBoolean Function**\n\n`); hoverContent.appendMarkdown(`${vscode.l10n.t(item.description)}\n\n`); if (item.version) { hoverContent.appendMarkdown(`*Version: ${item.version}*\n\n`); } if (item.example) { hoverContent.appendMarkdown(`\`\`\`ini\n${vscode.l10n.t(item.example)}\n\`\`\``); } return new vscode.Hover(hoverContent); } } } catch (error) { console.error('Error reading logicboolean.json:', error); } // 如果没有找到特定的函数,显示通用的LogicBoolean信息 const hoverContent = new vscode.MarkdownString(); hoverContent.appendMarkdown(`**LogicBoolean**\n\n`); hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.logicboolean.example.documentation')); return new vscode.Hover(hoverContent); } /** * 创建布尔值悬停信息 * @param word 单词 * @returns 悬停信息 */ private createBooleanValueHover(word: string): vscode.Hover | null { const trimmedValue = word.trim(); if (trimmedValue === 'true' || trimmedValue === 'false') { const hoverContent = new vscode.MarkdownString(); hoverContent.appendMarkdown(`**${vscode.l10n.t('valuecompletionprovider.bool.detail')}**\n\n`); if (trimmedValue === 'true') { hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.true.description')); } else { hoverContent.appendMarkdown(vscode.l10n.t('valuecompletionprovider.false.description')); } return new vscode.Hover(hoverContent); } return null; } }
2303_806435pww/RustedWarfareModSupport_moved
src/hoverProvider.ts
TypeScript
agpl-3.0
18,283
import * as vscode from 'vscode'; import { getSectionProperties } from '../dataProcessor'; /** * 基础值补全提供者抽象类 * 用于在属性值位置提供补全建议 */ export abstract class BaseValueCompletionProvider implements vscode.CompletionItemProvider { provideCompletionItems( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { // 检查当前位置是否在属性值位置(冒号后面) const lineText = document.lineAt(position.line).text; const textBeforeCursor = lineText.substring(0, position.character); // 查找冒号位置 const colonIndex = textBeforeCursor.lastIndexOf(':'); if (colonIndex === -1) { return []; } // 提取属性名称 let propertyText = textBeforeCursor.substring(0, colonIndex).trim(); // 处理可能的前缀,如 autoTrigger: const prefixPattern = /^([a-zA-Z0-9]+:\s*)+/; // 匹配类似 "prefix1: prefix2: " 的结构 propertyText = propertyText.replace(prefixPattern, '').trim(); if (!propertyText) { return []; } // 确定当前所在的节 const currentSection = this.getCurrentSection(document, position); if (!currentSection) { return []; } // 获取节的属性数据 const properties = getSectionProperties(currentSection); const property = properties.find((p: any) => p.name === propertyText); // 如果属性不存在,返回空 if (!property) { return []; } // 调用子类的具体实现 return this.provideValueCompletionItems(document, position, property); } /** * 抽象方法,由子类实现具体的补全逻辑 */ protected abstract provideValueCompletionItems( document: vscode.TextDocument, position: vscode.Position, property: any ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList>; /** * 获取当前位置所在的节名称 * @param document 文档对象 * @param position 位置对象 * @returns 节名称,如果未找到则返回null */ protected getCurrentSection(document: vscode.TextDocument, position: vscode.Position): string | null { let stop = false; for (let i = position.line; i >= 0; i--) { const line = document.lineAt(i).text.trim(); if (line.startsWith('[') && line.endsWith(']')) { const sectionName = line.substring(1, line.length - 1); stop = true; return sectionName; } if (stop) break; } return null; } }
2303_806435pww/RustedWarfareModSupport_moved
src/valueComple/BaseValueCompletionProvider.ts
TypeScript
agpl-3.0
2,961
import * as vscode from 'vscode'; import { BaseValueCompletionProvider } from './BaseValueCompletionProvider'; /** * 布尔值补全提供者类 * 用于提供布尔类型属性的补全建议 */ export class BoolValueCompletionProvider extends BaseValueCompletionProvider { protected provideValueCompletionItems( document: vscode.TextDocument, position: vscode.Position, property: any ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { // 根据属性类型提供相应的补全项 if (property.type === 'bool') { return this.getBoolCompletionItems(); } return []; } /** * 获取布尔类型补全项 * @returns 布尔类型补全项数组 */ private getBoolCompletionItems(): vscode.CompletionItem[] { const trueItem = new vscode.CompletionItem('true', vscode.CompletionItemKind.Value); trueItem.detail = vscode.l10n.t('valuecompletionprovider.bool.detail'); trueItem.documentation = new vscode.MarkdownString(vscode.l10n.t('valuecompletionprovider.true.description')); const falseItem = new vscode.CompletionItem('false', vscode.CompletionItemKind.Value); falseItem.detail = vscode.l10n.t('valuecompletionprovider.bool.detail'); falseItem.documentation = new vscode.MarkdownString(vscode.l10n.t('valuecompletionprovider.false.description')); return [trueItem, falseItem]; } }
2303_806435pww/RustedWarfareModSupport_moved
src/valueComple/BoolValueCompletionProvider.ts
TypeScript
agpl-3.0
1,502
import * as vscode from "vscode"; import { BaseValueCompletionProvider } from "./BaseValueCompletionProvider"; import * as fs from "fs"; import * as path from "path"; /** * LogicBoolean值补全提供者类 * 用于提供LogicBoolean类型属性的补全建议 */ export class LogicBooleanValueCompletionProvider extends BaseValueCompletionProvider { protected provideValueCompletionItems( document: vscode.TextDocument, position: vscode.Position, property: any ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { if (property && property.type === "LogicBoolean") { return this.getBasicLogicBooleanCompletionItems(); } return []; } private getBasicLogicBooleanCompletionItems(): vscode.CompletionItem[] { const valuePath = path.join( __dirname, "..", "data", "value", "logicboolean.json" ); const valueData = JSON.parse(fs.readFileSync(valuePath, "utf8")); return valueData.data.map((item: any) => { const completionItem = new vscode.CompletionItem( item.name, vscode.CompletionItemKind.Value ); completionItem.detail = vscode.l10n.t(item.description); completionItem.documentation = new vscode.MarkdownString( vscode.l10n.t('valuecompletionprovider.logicboolean.documentation', [ vscode.l10n.t(item.description), item.version, vscode.l10n.t(item.example) ]) ); // 对于LogicBoolean类型,直接插入值而不是name=value格式 completionItem.insertText = new vscode.SnippetString(item.name); return completionItem; }); } }
2303_806435pww/RustedWarfareModSupport_moved
src/valueComple/LogicBooleanValueCompletionProvider.ts
TypeScript
agpl-3.0
1,661
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import { BaseValueCompletionProvider } from './BaseValueCompletionProvider'; import { l10n } from 'vscode'; /** * 单位生成类属性补全提供者类 * 用于提供spawnUnits、produceUnits等属性的补全建议 */ export class UnitSpawnCompletionProvider extends BaseValueCompletionProvider { // 支持单位生成语法的属性列表 private readonly unitSpawnProperties = [ 'spawnUnits', 'spawnUnit', 'produceUnits', 'addUnitsIntoTransport', 'attachments_addNewUnits' ]; protected provideValueCompletionItems( document: vscode.TextDocument, position: vscode.Position, property: any ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { // 检查是否为单位生成类属性 if (this.unitSpawnProperties.includes(property.name)) { const lineText = document.lineAt(position.line).text; const textBeforeCursor = lineText.substring(0, position.character); // 检查光标是否在值的括号内 const insideParentheses = this.isInsideParentheses(textBeforeCursor, lineText, position.character); if (insideParentheses) { // 提供参数补全项 return this.getUnitSpawnParamCompletionItems(property.name); } // 否则提供基本格式示例 return this.getUnitSpawnCompletionItems(property.name); } return []; } /** * 检查光标是否在属性值的括号内 * @param textBeforeCursor 光标前的文本 * @param lineText 整行文本 * @param cursorPosition 光标位置 * @returns 是否在括号内 */ private isInsideParentheses(textBeforeCursor: string, lineText: string, cursorPosition: number): boolean { // 查找属性值开始位置(冒号后) const colonIndex = textBeforeCursor.lastIndexOf(':'); if (colonIndex === -1) { return false; } // 从光标前的位置开始,反向遍历到:位置 for (let i = cursorPosition - 1; i > colonIndex; i--) { if (lineText[i] === '(') { return true; } else if (lineText[i] === ')') { return false; } } // 如果光标位置处有未闭合的括号,则在括号内 return false; } /** * 获取单位生成基本格式补全项 * @param propertyName 属性名称 * @returns 单位生成基本格式补全项数组 */ private getUnitSpawnCompletionItems(propertyName: string): vscode.CompletionItem[] { try { // 读取对应属性的值定义文件 const valueType = propertyName === 'spawnProjectiles' || propertyName === 'spawnProjectile' ? 'spawnProjectiles' : 'spawnUnits'; const valuePath = path.join(__dirname, '..', 'data', 'value', `${valueType}.json`); const valueData = JSON.parse(fs.readFileSync(valuePath, 'utf8')); // 创建一个示例补全项 const exampleItem = new vscode.CompletionItem( valueData.example.split(':')[1].trim(), vscode.CompletionItemKind.Value ); // 使用单独的键进行国际化 const exampleDetail = l10n.t('valuecompletionprovider.spawnunits.example.detail'); const exampleDocKey = 'valuecompletionprovider.spawnunits.example.documentation'; exampleItem.detail = exampleDetail; exampleItem.documentation = new vscode.MarkdownString( l10n.t(exampleDocKey, propertyName) ); return [exampleItem]; } catch (error) { return []; } } /** * 获取单位生成参数补全项(用于括号内) * @param propertyName 属性名称 * @returns 单位生成参数补全项数组 */ private getUnitSpawnParamCompletionItems(propertyName: string): vscode.CompletionItem[] { try { // 读取对应属性的值定义文件 const valueType = propertyName === 'spawnProjectiles' || propertyName === 'spawnProjectile' ? 'spawnProjectiles' : 'spawnUnits'; const valuePath = path.join(__dirname, '..', 'data', 'value', `${valueType}.json`); const valueData = JSON.parse(fs.readFileSync(valuePath, 'utf8')); // 为每个参数创建补全项 const paramItems: vscode.CompletionItem[] = []; if (valueData.data && Array.isArray(valueData.data)) { for (const param of valueData.data) { // 创建参数补全项,格式为 paramName= const paramItem = new vscode.CompletionItem(`${param.name}=`, vscode.CompletionItemKind.Property); paramItem.detail = param.type; paramItem.documentation = new vscode.MarkdownString( `${vscode.l10n.t(param.description)}\n\n*${vscode.l10n.t('valuecompletionprovider.spawnunits.version')}: ${param.version}*\n\n\`\`\`ini\n${vscode.l10n.t(param.example)}\n\`\`\`` ); // 根据参数类型设置插入文本 switch (param.type) { case 'bool': // 为布尔类型提供true/false选项 paramItem.insertText = new vscode.SnippetString( `${param.name}=\${1|${l10n.t('true')},${l10n.t('false')}|}` ); break; case 'float': case 'int': // 为数值类型提供数字占位符 paramItem.insertText = new vscode.SnippetString( `${param.name}=\${1:${l10n.t('number')}0}}` ); break; default: // 其他类型提供通用占位符 paramItem.insertText = new vscode.SnippetString( `${param.name}=\${1:${l10n.t('value')}}}` ); } paramItems.push(paramItem); } } return paramItems; } catch (error) { console.error(`Error reading value definition file:`, error); return []; } } }
2303_806435pww/RustedWarfareModSupport_moved
src/valueComple/UnitSpawnCompletionProvider.ts
TypeScript
agpl-3.0
6,894
import * as vscode from 'vscode'; import { BoolValueCompletionProvider } from './BoolValueCompletionProvider'; import { UnitSpawnCompletionProvider } from './UnitSpawnCompletionProvider'; import { LogicBooleanValueCompletionProvider } from './LogicBooleanValueCompletionProvider'; export class ValueCompletionProvider implements vscode.CompletionItemProvider { private providers: vscode.CompletionItemProvider[]; constructor() { this.providers = [ new BoolValueCompletionProvider(), new UnitSpawnCompletionProvider(), new LogicBooleanValueCompletionProvider(), ]; } provideCompletionItems( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext ): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> { const completions: vscode.CompletionItem[] = []; for (const provider of this.providers) { try { const providerCompletions = provider.provideCompletionItems(document, position, token, context); if (providerCompletions) { if (Array.isArray(providerCompletions)) { completions.push(...providerCompletions); } else if ('items' in providerCompletions) { completions.push(...providerCompletions.items); } } } catch (error) { console.error('ValueCompletionProvider: Error calling provider=', provider.constructor.name, 'error=', error); } } return completions; } }
2303_806435pww/RustedWarfareModSupport_moved
src/valueComple/valueCompletionProvider.ts
TypeScript
agpl-3.0
1,717
using Godot; using System; public partial class Killzone : Area2D { // Called when the node enters the scene tree for the first time. public override void _Ready() { } // Called every frame. 'delta' is the elapsed time since the previous frame. public override void _Process(double delta) { } private void _on_body_entered(Node body) { GD.Print("wocaonima"); } }
2303_806435pww/my-first-godot-game_moved
testgame/Killzone.cs
C#
cc0-1.0
382
using Godot; using System; public partial class Coin : Area2D { // Called when the node enters the scene tree for the first time. public override void _Ready() { GD.Print("youshit"); } // Connect("body_entered", this, nameof(_on_body_entered)); // 处理 'body_entered' 信号的方法 private void _on_body_entered(Node body) { GD.Print(body.Name+"获得了金币"); QueueFree(); } // Called every frame. 'delta' is the elapsed time since the previous frame. public override void _Process(double delta) { } }
2303_806435pww/my-first-godot-game_moved
testgame/scene/Coin.cs
C#
cc0-1.0
559
using Godot; using System; public partial class Player : CharacterBody2D { public const float Speed = 250.0f; public const float JumpVelocity = -375.0f; public override void _PhysicsProcess(double delta) { Vector2 velocity = Velocity; // Add the gravity. if (!IsOnFloor()) { velocity += GetGravity() * (float)delta; } // Handle Jump. if (Input.IsActionJustPressed("ui_accept") && IsOnFloor()) { velocity.Y = JumpVelocity; } // Get the input direction and handle the movement/deceleration. // As good practice, you should replace UI actions with custom gameplay actions. Vector2 direction = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down"); if (direction != Vector2.Zero) { velocity.X = direction.X * Speed; } else { velocity.X = Mathf.MoveToward(Velocity.X, 0, Speed); } Velocity = velocity; MoveAndSlide(); } }
2303_806435pww/my-first-godot-game_moved
testgame/scene/Player.cs
C#
cc0-1.0
885
extends Area2D @onready var game_manager: Node = %gameManager @onready var animation_player: AnimationPlayer = $AnimationPlayer # Called when the node enters the scene tree for the first time. func _ready() -> void: pass # Replace with function body. # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(delta: float) -> void: pass func _on_body_entered(body: Node2D) -> void: pass # Replace with function body. print("shabi"); animation_player.play("getcoin"); game_manager.add_point();
2303_806435pww/my-first-godot-game_moved
testgame/scene/coin.gd
GDScript
cc0-1.0
540
extends Node @onready var scorelabel: Label = $scorelabel var score=0; # Called when the node enters the scene tree for the first time. func add_point(): score+=1 scorelabel.text="you have get "+str(score)+" coins."
2303_806435pww/my-first-godot-game_moved
testgame/scene/game_manager.gd
GDScript
cc0-1.0
225
extends Area2D @onready var timer: Timer = $Timer # Called when the node enters the scene tree for the first time. func _ready() -> void: pass # Replace with function body. # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(delta: float) -> void: pass func _on_body_entered(body: Node2D) -> void: pass # Replace with function body. print("死了"); Engine.time_scale=0.5; body.get_node("player").queue_free(); body.character_body_2d.flip_v=1; body.velocity.y=-100; timer.start(); func _on_timer_timeout() -> void: pass # Replace with function body. Engine.time_scale=1; get_tree().reload_current_scene();
2303_806435pww/my-first-godot-game_moved
testgame/scene/killzone.gd
GDScript
cc0-1.0
666
extends AnimatableBody2D @onready var ray_castright: RayCast2D = $RayCastright @onready var ray_castleft: RayCast2D = $RayCastleft var direction =1; const SPEED=30; # Called when the node enters the scene tree for the first time. func _ready() -> void: pass # Replace with function body. # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(delta: float) -> void: if ray_castleft.is_colliding(): direction=1; elif ray_castright.is_colliding(): direction=-1; if direction: position.x+= direction * SPEED*delta; else: position.x+=direction*SPEED*delta;
2303_806435pww/my-first-godot-game_moved
testgame/scene/platform lr.gd
GDScript
cc0-1.0
603
extends CharacterBody2D const SPEED = 250.0 const JUMP_VELOCITY = -350.0 @onready var character_body_2d: AnimatedSprite2D = $CharacterBody2D func _physics_process(delta: float) -> void: # Add the gravity. if not is_on_floor(): velocity += get_gravity() * delta # Handle jump. if Input.is_action_just_pressed("jump") and is_on_floor(): velocity.y = JUMP_VELOCITY # Get the input direction and handle the movement/deceleration. # As good practice, you should replace UI actions with custom gameplay actions. var direction := Input.get_axis("left_move", "right_move") # return -1,0,1,i forgget it!! if direction>0: character_body_2d.flip_h=0 elif direction<0: character_body_2d.flip_h=1 if is_on_floor(): if direction==0: character_body_2d.play("move"); elif direction!=0: character_body_2d.play("run"); else: character_body_2d.play("jump"); if direction: velocity.x = direction * SPEED else: velocity.x = move_toward(velocity.x, 0, SPEED) move_and_slide()
2303_806435pww/my-first-godot-game_moved
testgame/scene/player.gd
GDScript
cc0-1.0
1,012
extends Node2D @onready var ray_cast_left: RayCast2D = $RayCastLeft @onready var ray_cast_right: RayCast2D = $RayCastRight @onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D const SPEED=30; var direction=1; # Called when the node enters the scene tree for the first time. func _ready() -> void: pass # Replace with function body. # Called every frame. 'delta' is the elap sed time since the previous frame. func _process(delta: float) -> void: if ray_cast_left.is_colliding()||ray_cast_right.is_colliding(): direction*=-1 animated_sprite_2d.flip_h=!animated_sprite_2d.flip_h position.x+=SPEED*delta*direction;
2303_806435pww/my-first-godot-game_moved
testgame/scene/slime.gd
GDScript
cc0-1.0
639
extends Sprite2D # Called when the node enters the scene tree for the first time. func _ready() -> void: pass # Replace with function body. # Called every frame. 'delta' is the elapsed time since the previous frame. func _process(delta: float) -> void: pass
2303_806435pww/my-first-godot-game_moved
testgame/scene/sprite_2d.gd
GDScript
cc0-1.0
266
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "crypt_eal_cipher.h" // Header file of the interfaces for symmetric encryption and decryption. #include "bsl_sal.h" #include "bsl_err.h" #include "crypt_algid.h" // Algorithm ID list. #include "crypt_errno.h" // Error code list. void *StdMalloc(uint32_t len) { return malloc((size_t)len); } void PrintLastError(void) { const char *file = NULL; uint32_t line = 0; BSL_ERR_GetLastErrorFileLine(&file, &line); // Obtain the name and number of lines of the error file. printf("failed at file %s at line %d\n", file, line); } int main(void) { uint8_t data[10] = {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x1c, 0x14}; uint8_t iv[16] = {0}; uint8_t key[16] = {0}; uint32_t dataLen = sizeof(data); uint8_t cipherText[100]; uint8_t plainText[100]; uint32_t outTotalLen = 0; uint32_t outLen = sizeof(cipherText); uint32_t cipherTextLen; int32_t ret; printf("plain text to be encrypted: "); for (uint32_t i = 0; i < dataLen; i++) { printf("%02x", data[i]); } printf("\n"); // Create a context. CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_CipherNewCtx( CRYPT_CIPHER_AES128_CBC); if (ctx == NULL) { PrintLastError(); BSL_ERR_DeInit(); return 1; } /* * During initialization, the last input parameter can be true or false. true indicates encryption, * and false indicates decryption. */ ret = CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), true); if (ret != CRYPT_SUCCESS) { // Output the error code. You can find the error information in **crypt_errno.h** based on the error code. printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the padding mode. ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } /** * Enter the data to be calculated. This interface can be called for multiple times. * The input value of **outLen** is the length of the ciphertext, * and the output value is the amount of processed data. * */ ret = CRYPT_EAL_CipherUpdate(ctx, data, dataLen, cipherText, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; outLen = sizeof(cipherText) - outTotalLen; ret = CRYPT_EAL_CipherFinal(ctx, cipherText + outTotalLen, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; printf("cipher text value is: "); for (uint32_t i = 0; i < outTotalLen; i++) { printf("%02x", cipherText[i]); } printf("\n"); // Start decryption. cipherTextLen = outTotalLen; outTotalLen = 0; outLen = sizeof(plainText); // When initializing the decryption function, set the last input parameter to false. ret = CRYPT_EAL_CipherInit(ctx, key, sizeof(key), iv, sizeof(iv), false); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Set the padding mode, which must be the same as that for encryption. ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } // Enter the ciphertext data. ret = CRYPT_EAL_CipherUpdate(ctx, cipherText, cipherTextLen, plainText, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; outLen = sizeof(plainText) - outTotalLen; // Decrypt the last segment of data and remove the filled content. ret = CRYPT_EAL_CipherFinal(ctx, plainText + outTotalLen, &outLen); if (ret != CRYPT_SUCCESS) { printf("error code is %x\n", ret); PrintLastError(); goto EXIT; } outTotalLen += outLen; printf("decrypted plain text value is: "); for (uint32_t i = 0; i < outTotalLen; i++) { printf("%02x", plainText[i]); } printf("\n"); if (outTotalLen != dataLen || memcmp(plainText, data, dataLen) != 0) { printf("plaintext comparison failed\n"); goto EXIT; } printf("pass \n"); EXIT: CRYPT_EAL_CipherFreeCtx(ctx); BSL_ERR_DeInit(); return ret; }
2302_82127028/openHiTLS-examples_1508
AES.c
C
unknown
5,192
# This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. cmake_minimum_required(VERSION 3.16 FATAL_ERROR) project(openHiTLS) set(HiTLS_SOURCE_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}) if(DEFINED BUILD_DIR) set(HiTLS_BUILD_DIR ${BUILD_DIR}) else() set(HiTLS_BUILD_DIR ${HiTLS_SOURCE_ROOT_DIR}/build) endif() execute_process(COMMAND python3 ${HiTLS_SOURCE_ROOT_DIR}/configure.py -m --build_dir ${HiTLS_BUILD_DIR}) include(${HiTLS_BUILD_DIR}/modules.cmake) install(DIRECTORY ${HiTLS_SOURCE_ROOT_DIR}/include/ DESTINATION ${CMAKE_INSTALL_PREFIX}/include/hitls/ FILES_MATCHING PATTERN "*.h")
2302_82127028/openHiTLS-examples_1508
CMakeLists.txt
CMake
unknown
1,079
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_CONF_H #define HITLS_APP_CONF_H #include <stdint.h> #include "bsl_obj.h" #include "bsl_conf.h" #include "hitls_pki_types.h" #include "hitls_pki_utils.h" #include "hitls_pki_csr.h" #include "hitls_pki_cert.h" #include "hitls_pki_crl.h" #include "hitls_pki_x509.h" #include "hitls_pki_pkcs12.h" #ifdef __cplusplus extern "C" { #endif /** * x509 v3 extensions */ #define HITLS_CFG_X509_EXT_AKI "authorityKeyIdentifier" #define HITLS_CFG_X509_EXT_SKI "subjectKeyIdentifier" #define HITLS_CFG_X509_EXT_BCONS "basicConstraints" #define HITLS_CFG_X509_EXT_KU "keyUsage" #define HITLS_CFG_X509_EXT_EXKU "extendedKeyUsage" #define HITLS_CFG_X509_EXT_SAN "subjectAltName" /* Key usage */ #define HITLS_CFG_X509_EXT_KU_DIGITAL_SIGN "digitalSignature" #define HITLS_CFG_X509_EXT_KU_NON_REPUDIATION "nonRepudiation" #define HITLS_CFG_X509_EXT_KU_KEY_ENCIPHERMENT "keyEncipherment" #define HITLS_CFG_X509_EXT_KU_DATA_ENCIPHERMENT "dataEncipherment" #define HITLS_CFG_X509_EXT_KU_KEY_AGREEMENT "keyAgreement" #define HITLS_CFG_X509_EXT_KU_KEY_CERT_SIGN "keyCertSign" #define HITLS_CFG_X509_EXT_KU_CRL_SIGN "cRLSign" #define HITLS_CFG_X509_EXT_KU_ENCIPHER_ONLY "encipherOnly" #define HITLS_CFG_X509_EXT_KU_DECIPHER_ONLY "decipherOnly" /* Extended key usage */ #define HITLS_CFG_X509_EXT_EXKU_SERVER_AUTH "serverAuth" #define HITLS_CFG_X509_EXT_EXKU_CLIENT_AUTH "clientAuth" #define HITLS_CFG_X509_EXT_EXKU_CODE_SING "codeSigning" #define HITLS_CFG_X509_EXT_EXKU_EMAIL_PROT "emailProtection" #define HITLS_CFG_X509_EXT_EXKU_TIME_STAMP "timeStamping" #define HITLS_CFG_X509_EXT_EXKU_OCSP_SIGN "OCSPSigning" /* Subject Alternative Name */ #define HITLS_CFG_X509_EXT_SAN_EMAIL "email" #define HITLS_CFG_X509_EXT_SAN_DNS "DNS" #define HITLS_CFG_X509_EXT_SAN_DIR_NAME "dirName" #define HITLS_CFG_X509_EXT_SAN_URI "URI" #define HITLS_CFG_X509_EXT_SAN_IP "IP" /* Authority key identifier */ #define HITLS_CFG_X509_EXT_AKI_KID (1 << 0) #define HITLS_CFG_X509_EXT_AKI_KID_ALWAYS (1 << 1) typedef struct { HITLS_X509_ExtAki aki; uint32_t flag; } HITLS_CFG_ExtAki; /** * @ingroup apps * * @brief Split String by character. * Remove spaces before and after separators. * * @param str [IN] String to be split. * @param separator [IN] Separator. * @param allowEmpty [IN] Indicates whether empty substrings can be contained. * @param strArr [OUT] String array. Only the first string needs to be released after use. * @param maxArrCnt [IN] String array. Only the first string needs to be released after use. * @param realCnt [OUT] Number of character strings after splitting。 * * @retval HITLS_APP_SUCCESS */ int32_t HITLS_APP_SplitString(const char *str, char separator, bool allowEmpty, char **strArr, uint32_t maxArrCnt, uint32_t *realCnt); /** * @ingroup apps * * @brief Process function of X509 extensions. * * @param cid [IN] Cid of extension * @param val [IN] Data pointer. * @param ctx [IN] Context. * * @retval HITLS_APP_SUCCESS */ typedef int32_t (*ProcExtCallBack)(BslCid cid, void *val, void *ctx); /** * @ingroup apps * * @brief Process function of X509 extensions. * * @param value [IN] conf * @param section [IN] The section name of x509 extension * @param extCb [IN] Callback function of one extension. * @param ctx [IN] Context of callback function. * * @retval HITLS_APP_SUCCESS */ int32_t HITLS_APP_CONF_ProcExt(BSL_CONF *cnf, const char *section, ProcExtCallBack extCb, void *ctx); /** * @ingroup apps * * @brief The callback function to add distinguish name * * @param ctx [IN] The context of callback function * @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN * * @retval HITLS_APP_SUCCESS */ typedef int32_t (*AddDnNameCb)(void *ctx, BslList *nameList); /** * @ingroup apps * * @brief The callback function to add subject name to csr * * @param ctx [IN] The context of callback function * @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN * * @retval HITLS_APP_SUCCESS */ int32_t HiTLS_AddSubjDnNameToCsr(void *csr, BslList *nameList); /** * @ingroup apps * * @brief Process distinguish name string. * The distinguish name format is /type0=value0/type1=value1/type2=... * * @param nameStr [IN] distinguish name string * @param cb [IN] The callback function to add distinguish name to csr or cert * @param ctx [IN] Context of callback function. * * @retval HITLS_APP_SUCCESS */ int32_t HITLS_APP_CFG_ProcDnName(const char *nameStr, AddDnNameCb cb, void *ctx); #ifdef __cplusplus } #endif #endif // HITLS_APP_CONF_H
2302_82127028/openHiTLS-examples_1508
apps/include/app_conf.h
C
unknown
5,429
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_CRL_H #define HITLS_APP_CRL_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int32_t HITLS_CrlMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_crl.h
C
unknown
734
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_DGST_H #define HITLS_APP_DGST_H #include <stdint.h> #include <stddef.h> #include "crypt_algid.h" #ifdef __cplusplus extern "C" { #endif typedef struct { const int mdId; const char *mdAlgName; } HITLS_AlgList; int32_t HITLS_DgstMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_dgst.h
C
unknown
866
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_ENC_H #define HITLS_APP_ENC_H #include <stdint.h> #include <linux/limits.h> #ifdef __cplusplus extern "C" { #endif #define REC_ITERATION_TIMES 10000 #define REC_MAX_FILE_LENGEN 512 #define REC_MAX_FILENAME_LENGTH PATH_MAX #define REC_MAX_MAC_KEY_LEN 64 #define REC_MAX_KEY_LENGTH 64 #define REC_MAX_IV_LENGTH 16 #define REC_HEX_BASE 16 #define REC_SALT_LEN 8 #define REC_HEX_BUF_LENGTH 8 #define REC_MIN_PRE_LENGTH 6 #define REC_DOUBLE 2 #define MAX_BUFSIZE 4096 #define XTS_MIN_DATALEN 16 #define BUF_SAFE_BLOCK 16 #define BUF_READABLE_BLOCK 32 #define IS_SUPPORT_GET_EOF 1 #define BSL_SUCCESS 0 typedef enum { HITLS_APP_OPT_CIPHER_ALG = 2, HITLS_APP_OPT_IN_FILE, HITLS_APP_OPT_OUT_FILE, HITLS_APP_OPT_DEC, HITLS_APP_OPT_ENC, HITLS_APP_OPT_MD, HITLS_APP_OPT_PASS, } HITLS_OptType; typedef struct { const int cipherId; const char *cipherAlgName; } HITLS_CipherAlgList; typedef struct { const int macId; const char *macAlgName; } HITLS_MacAlgList; int32_t HITLS_EncMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_enc.h
C
unknown
1,853
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_ERRNO_H #define HITLS_APP_ERRNO_H #ifdef __cplusplus extern "C" { #endif #define HITLS_APP_SUCCESS 0 // The return value of HITLS APP ranges from 0, 1, 3 to 125. // 3 to 125 are external error codes. enum HITLS_APP_ERROR { HITLS_APP_HELP = 0x1, /* *< the subcommand has the help option */ HITLS_APP_SECUREC_FAIL, /* *< error returned by the safe function */ HITLS_APP_MEM_ALLOC_FAIL, /* *< failed to apply for memory resources */ HITLS_APP_INVALID_ARG, /* *< invalid parameter */ HITLS_APP_INTERNAL_EXCEPTION, HITLS_APP_ENCODE_FAIL, /* *< encodeing failure */ HITLS_APP_CRYPTO_FAIL, HITLS_APP_PASSWD_FAIL, HITLS_APP_UIO_FAIL, HITLS_APP_STDIN_FAIL, /* *< incorrect stdin input */ HITLS_APP_INFO_CMP_FAIL, /* *< failed to match the received information with the parameter */ HITLS_APP_INVALID_DN_TYPE, HITLS_APP_INVALID_DN_VALUE, HITLS_APP_INVALID_GENERAL_NAME_TYPE, HITLS_APP_INVALID_GENERAL_NAME, HITLS_APP_INVALID_IP, HITLS_APP_ERR_CONF_GET_SECTION, HITLS_APP_NO_EXT, HITLS_APP_INIT_FAILED, HITLS_APP_COPY_ARGS_FAILED, HITLS_APP_OPT_UNKOWN, /* *< option error */ HITLS_APP_OPT_NAME_INVALID, /* *< the subcommand name is invalid */ HITLS_APP_OPT_VALUETYPE_INVALID, /* *< the parameter type of the subcommand is invalid */ HITLS_APP_OPT_TYPE_INVALID, /* *< the subcommand type is invalid */ HITLS_APP_OPT_VALUE_INVALID, /* *< the subcommand parameter value is invalid */ HITLS_APP_DECODE_FAIL, /* *< decoding failure */ HITLS_APP_CERT_VERIFY_FAIL, /* *< certificate verification failed */ HITLS_APP_X509_FAIL, /* *< x509-related error. */ HITLS_APP_SAL_FAIL, /* *< sal-related error. */ HITLS_APP_BSL_FAIL, /* *< bsl-related error. */ HITLS_APP_CONF_FAIL, /* *< conf-related error. */ HITLS_APP_LOAD_CERT_FAIL, /* *< Failed to load the cert. */ HITLS_APP_LOAD_CSR_FAIL, /* *< Failed to load the csr. */ HITLS_APP_LOAD_KEY_FAIL, /* *< Failed to load the public and private keys. */ HITLS_APP_ENCODE_KEY_FAIL, /* *< Failed to encode the public and private keys. */ HITLS_APP_MAX = 126, /* *< maximum of the error code */ }; #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_errno.h
C
unknown
3,087
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_FUNCTION_H #define HITLS_APP_FUNCTION_H #ifdef __cplusplus extern "C" { #endif typedef enum { FUNC_TYPE_NONE, // default FUNC_TYPE_GENERAL, // general command } HITLS_CmdFuncType; typedef struct { const char *name; // second-class command name HITLS_CmdFuncType type; // type of command int (*main)(int argc, char *argv[]); // second-class entry function } HITLS_CmdFunc; int AppGetProgFunc(const char *proName, HITLS_CmdFunc *func); void AppPrintFuncList(void); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_function.h
C
unknown
1,129
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_GENPKEY_H #define HITLS_APP_GENPKEY_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int32_t HITLS_GenPkeyMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif // HITLS_APP_Genpkey_H
2302_82127028/openHiTLS-examples_1508
apps/include/app_genpkey.h
C
unknown
769
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_GENRSA_H #define HITLS_APP_GENRSA_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define REC_MAX_PEM_FILELEN 65537 #define REC_MAX_PKEY_LENGTH 16384 #define REC_MIN_PKEY_LENGTH 512 #define REC_ALG_NUM_EACHLINE 4 typedef struct { const int id; const char *algName; } HITLS_APPAlgList; int32_t HITLS_GenRSAMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_genrsa.h
C
unknown
967
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_HELP_H #define HITLS_APP_HELP_H #ifdef __cplusplus extern "C" { #endif int HITLS_HelpMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_help.h
C
unknown
714
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_KDF_H #define HITLS_APP_KDF_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int32_t HITLS_KdfMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_kdf.h
C
unknown
734
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_LIST_H #define HITLS_APP_LIST_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef enum { HITLS_APP_LIST_OPT_ALL_ALG = 2, HITLS_APP_LIST_OPT_DGST_ALG, HITLS_APP_LIST_OPT_CIPHER_ALG, HITLS_APP_LIST_OPT_ASYM_ALG, HITLS_APP_LIST_OPT_MAC_ALG, HITLS_APP_LIST_OPT_RAND_ALG, HITLS_APP_LIST_OPT_KDF_ALG, HITLS_APP_LIST_OPT_CURVES } HITLSListOptType; int HITLS_ListMain(int argc, char *argv[]); int32_t HITLS_APP_GetCidByName(const char *name, int32_t type); const char *HITLS_APP_GetNameByCid(int32_t cid, int32_t type); #ifdef __cplusplus } #endif #endif // HITLS_APP_LIST_H
2302_82127028/openHiTLS-examples_1508
apps/include/app_list.h
C
unknown
1,183
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_MAC_H #define HITLS_APP_MAC_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int32_t HITLS_MacMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_mac.h
C
unknown
734
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_OPT_H #define HITLS_APP_OPT_H #include <stdint.h> #include "bsl_uio.h" #include "bsl_types.h" #ifdef __cplusplus extern "C" { #endif #define HILTS_APP_FORMAT_UNDEF 0 #define HITLS_APP_FORMAT_PEM BSL_FORMAT_PEM // 1 #define HITLS_APP_FORMAT_ASN1 BSL_FORMAT_ASN1 // 2 #define HITLS_APP_FORMAT_TEXT 3 #define HITLS_APP_FORMAT_BASE64 4 #define HITLS_APP_FORMAT_HEX 5 #define HITLS_APP_FORMAT_BINARY 6 #define HITLS_APP_PROV_ENUM \ HITLS_APP_OPT_PROVIDER, \ HITLS_APP_OPT_PROVIDER_PATH, \ HITLS_APP_OPT_PROVIDER_ATTR \ #define HITLS_APP_PROV_OPTIONS \ {"provider", HITLS_APP_OPT_PROVIDER, HITLS_APP_OPT_VALUETYPE_STRING, \ "Specify the cryptographic service provider"}, \ {"provider-path", HITLS_APP_OPT_PROVIDER_PATH, HITLS_APP_OPT_VALUETYPE_STRING, \ "Set the path to the cryptographic service provider"}, \ {"provider-attr", HITLS_APP_OPT_PROVIDER_ATTR, HITLS_APP_OPT_VALUETYPE_STRING, \ "Set additional attributes for the cryptographic service provider"} \ #define HITLS_APP_PROV_CASES(optType, provider) \ switch (optType) { \ case HITLS_APP_OPT_PROVIDER: \ (provider)->providerName = HITLS_APP_OptGetValueStr(); \ break; \ case HITLS_APP_OPT_PROVIDER_PATH: \ (provider)->providerPath = HITLS_APP_OptGetValueStr(); \ break; \ case HITLS_APP_OPT_PROVIDER_ATTR: \ (provider)->providerAttr = HITLS_APP_OptGetValueStr(); \ break; \ default: \ break; \ } typedef enum { HITLS_APP_OPT_VALUETYPE_NONE = 0, HITLS_APP_OPT_VALUETYPE_NO_VALUE = 1, HITLS_APP_OPT_VALUETYPE_IN_FILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, HITLS_APP_OPT_VALUETYPE_STRING, HITLS_APP_OPT_VALUETYPE_PARAMTERS, HITLS_APP_OPT_VALUETYPE_DIR, HITLS_APP_OPT_VALUETYPE_INT, HITLS_APP_OPT_VALUETYPE_UINT, HITLS_APP_OPT_VALUETYPE_POSITIVE_INT, HITLS_APP_OPT_VALUETYPE_LONG, HITLS_APP_OPT_VALUETYPE_ULONG, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, HITLS_APP_OPT_VALUETYPE_FMT_ANY, HITLS_APP_OPT_VALUETYPE_MAX, } HITLS_ValueType; typedef enum { HITLS_APP_OPT_VALUECLASS_NONE = 0, HITLS_APP_OPT_VALUECLASS_NO_VALUE = 1, HITLS_APP_OPT_VALUECLASS_STR, HITLS_APP_OPT_VALUECLASS_DIR, HITLS_APP_OPT_VALUECLASS_INT, HITLS_APP_OPT_VALUECLASS_LONG, HITLS_APP_OPT_VALUECLASS_FMT, HITLS_APP_OPT_VALUECLASS_MAX, } HITLS_ValueClass; typedef enum { HITLS_APP_OPT_ERR = -1, HITLS_APP_OPT_EOF = 0, HITLS_APP_OPT_PARAM = HITLS_APP_OPT_EOF, HITLS_APP_OPT_HELP = 1, } HITLS_OptChoice; typedef struct { const char *name; // option name const int optType; // option type int valueType; // options with parameters(type) const char *help; // description of this option } HITLS_CmdOption; /** * @ingroup HITLS_APP * @brief Initialization of command-line argument parsing (internal function) * * @param argc [IN] number of options * @param argv [IN] pointer to an array of options * @param opts [IN] command option table * * @retval command name of command-line argument */ int32_t HITLS_APP_OptBegin(int32_t argc, char **argv, const HITLS_CmdOption *opts); /** * @ingroup HITLS_APP * @brief Parse next command-line argument (internal function) * * @param void * * @retval int32 option type */ int32_t HITLS_APP_OptNext(void); /** * @ingroup HITLS_APP * @brief Finish parsing options * * @param void * * @retval void */ void HITLS_APP_OptEnd(void); /** * @ingroup HITLS_APP * @brief Print command line parsing * * @param opts command option table * * @retval void */ void HITLS_APP_OptHelpPrint(const HITLS_CmdOption *opts); /** * @ingroup HITLS_APP * @brief Get the number of remaining options * * @param void * * @retval int32 number of remaining options */ int32_t HITLS_APP_GetRestOptNum(void); /** * @ingroup HITLS_APP * @brief Get the remaining options * * @param void * * @retval char** the address of remaining options */ char **HITLS_APP_GetRestOpt(void); /** * @ingroup HITLS_APP * @brief Get command option * @param void * @retval char* command option */ char *HITLS_APP_OptGetValueStr(void); /** * @ingroup HITLS_APP * @brief option string to int * @param valueS [IN] string value * @param valueL [OUT] int value * @retval int32_t success or not */ int32_t HITLS_APP_OptGetInt(const char *valueS, int32_t *valueI); /** * @ingroup HITLS_APP * @brief option string to uint32_t * @param valueS [IN] string value * @param valueL [OUT] uint32_t value * @retval int32_t success or not */ int32_t HITLS_APP_OptGetUint32(const char *valueS, uint32_t *valueU); /** * @ingroup HITLS_APP * @brief Get the name of the current second-class command * * @param void * * @retval char* command name */ char *HITLS_APP_GetProgName(void); /** * @ingroup HITLS_APP * @brief option string to long * * @param valueS [IN] string value * @param valueL [OUT] long value * * @retval int32_t success or not */ int32_t HITLS_APP_OptGetLong(const char *valueS, long *valueL); /** * @ingroup HITLS_APP * @brief Get the format type from the option value * * @param valueS [IN] string of value * @param type [IN] value type * @param formatType [OUT] format type * * @retval int32_t success or not */ int32_t HITLS_APP_OptGetFormatType(const char *valueS, HITLS_ValueType type, BSL_ParseFormat *formatType); /** * @ingroup HITLS_APP * @brief Get UIO type from option value * * @param filename [IN] name of input file * @param mode [IN] method of opening a file * @param flag [OUT] whether the closing of the standard input/output window is bound to the UIO * * @retval BSL_UIO * when succeeded, NULL when failed */ BSL_UIO* HITLS_APP_UioOpen(const char* filename, char mode, int32_t flag); /** * @ingroup HITLS_APP * @brief Converts a character string to a character string in Base64 format and output the buf to UIO * * @param buf [IN] content to be encoded * @param inBufLen [IN] the length of content to be encoded * @param outBuf [IN] Encoded content * @param outBufLen [IN] the length of encoded content * * @retval int32_t success or not */ int32_t HITLS_APP_OptToBase64(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen); /** * @ingroup HITLS_APP * @brief Converts a character string to a hexadecimal character string and output the buf to UIO * * @param buf [IN] content to be encoded * @param inBufLen [IN] the length of content to be encoded * @param outBuf [IN] Encoded content * @param outBufLen [IN] the length of encoded content * * @retval int32_t success or not */ int32_t HITLS_APP_OptToHex(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen); /** * @ingroup HITLS_APP * @brief Output the buf to UIO * * @param uio [IN] output UIO * @param buf [IN] output buf * @param outLen [IN] the length of output buf * @param format [IN] output format * * @retval int32_t success or not */ int32_t HITLS_APP_OptWriteUio(BSL_UIO* uio, uint8_t* buf, uint32_t outLen, int32_t format); /** * @ingroup HITLS_APP * @brief Read the content in the UIO to the readBuf * * @param uio [IN] input UIO * @param readBuf [IN] buf which uio read * @param readBufLen [IN] the length of readBuf * @param maxBufLen [IN] the maximum length to be read. * * @retval int32_t success or not */ int32_t HITLS_APP_OptReadUio(BSL_UIO *uio, uint8_t **readBuf, uint64_t *readBufLen, uint64_t maxBufLen); /** * @ingroup HITLS_APP * @brief Get unknown option name * * @retval char* */ const char *HITLS_APP_OptGetUnKownOptName(); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_opt.h
C
unknown
8,603
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_PASSWD_H #define HITLS_APP_PASSWD_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif #define REC_MAX_ITER_TIMES 999999999 #define REC_DEF_ITER_TIMES 5000 #define REC_MAX_ARRAY_LEN 1025 #define REC_MIN_ITER_TIMES 1000 #define REC_SHA512_BLOCKSIZE 64 #define REC_HASH_BUF_LEN 64 #define REC_MIN_PREFIX_LEN 37 #define REC_MAX_SALTLEN 16 #define REC_SHA512_SALTLEN 16 #define REC_TEN 10 #define REC_PRE_ITER_LEN 8 #define REC_SEVEN 7 #define REC_SHA512_ALGTAG 6 #define REC_SHA256_ALGTAG 5 #define REC_PRE_TAG_LEN 3 #define REC_THREE 3 #define REC_TWO 2 #define REC_MD5_ALGTAG 1 int32_t HITLS_PasswdMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_passwd.h
C
unknown
1,429
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_PKCS12_H #define HITLS_APP_PKCS12_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int32_t HITLS_PKCS12Main(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_pkcs12.h
C
unknown
745
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_PKEY_H #define HITLS_APP_PKEY_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int32_t HITLS_PkeyMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif // HITLS_APP_PKEY_H
2302_82127028/openHiTLS-examples_1508
apps/include/app_pkey.h
C
unknown
757
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_LOG_H #define HITLS_APP_LOG_H #include <stdio.h> #include <stdint.h> #include "bsl_uio.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup HITLS_APPS * @brief Print output to UIO * * @param uio [IN] UIO to be printed * @param format [IN] Log format character string * @param... [IN] format Parameter * @retval int32_t */ int32_t AppPrint(BSL_UIO *uio, const char *format, ...); /** * @ingroup HiTLS_APPS * @brief Print the output to stderr. * * @param format [IN] Log format character string * @param... [IN] format Parameter * @retval void */ void AppPrintError(const char *format, ...); /** * @ingroup HiTLS_APPS * @brief Initialize the PrintErrUIO. * * @param fp [IN] File pointer, for example, stderr. * @retval int32_t */ int32_t AppPrintErrorUioInit(FILE *fp); /** * @ingroup HiTLS_APPS * @brief Deinitialize the PrintErrUIO. * * @retval void */ void AppPrintErrorUioUnInit(void); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_print.h
C
unknown
1,527
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_PROVIDER_H #define HITLS_APP_PROVIDER_H #include <stdint.h> #include "crypt_types.h" #include "crypt_eal_provider.h" #ifdef __cplusplus extern "C" { #endif typedef struct { char *providerName; char *providerPath; char *providerAttr; } AppProvider; CRYPT_EAL_LibCtx *APP_Create_LibCtx(void); CRYPT_EAL_LibCtx *APP_GetCurrent_LibCtx(void); int32_t HITLS_APP_LoadProvider(const char *searchPath, const char *providerName); #define HITLS_APP_FreeLibCtx CRYPT_EAL_LibCtxFree #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_provider.h
C
unknown
1,083
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef HITLS_APP_RAND_H #define HITLS_APP_RAND_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif int32_t HITLS_RandMain(int argc, char *argv[]); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_1508
apps/include/app_rand.h
C
unknown
737