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. */ /* BEGIN_HEADER */ #include <semaphore.h> #include <unistd.h> #include "securec.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_session.h" #include "hitls_error.h" #include "session.h" #include "hlt.h" #include "alert.h" #include "frame_msg.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "simulate_io.h" #include "process.h" #include "hitls_type.h" #include "session_type.h" #include "cert_mgr.h" #include "cert_mgr_ctx.h" #include "hitls_cert_type.h" #include "hs_extensions.h" #include "rec_wrapper.h" /* END_HEADER */ static uint32_t g_uiPort = 2569; #define READ_BUF_SIZE 20 #define TEMP_DATA_LEN 1024 int32_t GetSessionCacheMode(HLT_Ctx_Config *config) { return config->setSessionCache; } static void FrameCallBack_SerrverHello_MasteKey_Add(void *msg, void *userData) { // ServerHello exception: The masterkey extension is added to the sent ServerHello message. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ServerHelloMsg *serverhello = &frameMsg->body.hsMsg.body.serverHello; serverhello->extensionLen.state = INITIAL_FIELD; serverhello->extendedMasterSecret.exState = INITIAL_FIELD; serverhello->extendedMasterSecret.exType.state = INITIAL_FIELD; serverhello->extendedMasterSecret.exType.data = HS_EX_TYPE_EXTENDED_MASTER_SECRET; serverhello->extendedMasterSecret.exLen.state = INITIAL_FIELD; serverhello->extendedMasterSecret.exLen.data = 0u; EXIT: return; } static void FrameCallBack_SerrverHello_MasteKey_MISS(void *msg, void *userData) { HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ServerHelloMsg *serverhello = &frameMsg->body.hsMsg.body.serverHello; serverhello->extendedMasterSecret.exState = MISSING_FIELD; EXIT: return; } /** @ * @test SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC006 * @title When the session is resumed, the client receives the server hello message that carries the master key * extension. * @precon nan * @brief 1. The client and server do not support the extension connection establishment. Expected result 1 is * obtained. * 2. Disconnect the connection, save the session, and restore the session. * 3. During session restoration, modify the server hello message to carry the master secret extension. * Expected result 2 is obtained. * 4. Establish a connection and observe the connection establishment status. (Expected result 3) * @expect 1. The connection is set up successfully. * 2. The modification is successful. * 3. Session restoration fails and the handshake is interrupted. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC006(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; int32_t cnt = 1; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_SetExtenedMasterSecretSupport(clientCtxConfig, false); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // 1. The client and server do not support the extension connection establishment. HLT_SetExtenedMasterSecretSupport(clientCtxConfig, false); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = g_uiPort; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { HLT_CleanFrameHandle(); HLT_FrameHandle handle = {0}; handle.pointType = POINT_RECV; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; // 3. During session restoration, modify the server hello message to carry the master key extension. handle.frameCallBack = FrameCallBack_SerrverHello_MasteKey_Add; handle.ctx = clientSsl; ASSERT_TRUE(HLT_SetFrameHandle(&handle) == 0); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); // 4. Establish a connection and observe the connection establishment status. ASSERT_TRUE(HLT_TlsConnect(clientSsl) != 0); } else { ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); // 2. Disconnect the connection, save the session, and restore the session. ASSERT_TRUE(HLT_RpcTlsClose(remoteProcess, serverSslId) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt < 3); EXIT: HLT_CleanFrameHandle(); HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC007 * @title When the session is resumed, the client receives a server hello message that does not carry the master key * extension. * @precon nan * @brief 1. The client and server support the extension connection establishment. Expected result 1 is obtained. * 2. Disconnect the connection, save the session, and restore the session. * 3. During session recovery, modify the server hello command on the server to cause the master key extension * to be lost. Expected result 2 is obtained. * 4. Establish a connection and observe the connection setup status. (Expected result 3) * @expect 1. The connection is set up successfully. * 2. The modification is successful. * 3. Session restoration fails and the handshake is interrupted. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC007(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; int32_t cnt = 1; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = g_uiPort; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { HLT_CleanFrameHandle(); HLT_FrameHandle handle = {0}; handle.pointType = POINT_RECV; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; /* 3. During session recovery, modify the server hello command on the server to cause the master key * extension to be lost. */ handle.frameCallBack = FrameCallBack_SerrverHello_MasteKey_MISS; handle.ctx = clientSsl; ASSERT_TRUE(HLT_SetFrameHandle(&handle) == 0); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); // 4. Establish a connection and observe the connection setup status. ASSERT_TRUE(HLT_TlsConnect(clientSsl) != 0); } else { // 1. The client and server support the extension connection establishment. ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_RpcTlsClose(remoteProcess, serverSslId) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); // 2. Disconnect the connection, save the session, and restore the session. HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt < 3); EXIT: HLT_CleanFrameHandle(); HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC008 * @title Resume sessions on servers that do not support session recovery. * @precon nan * @brief 1. The client and server support the extension connection establishment. Disconnect the connection and save * the session. * 2. Apply for another server that does not support the extension and establish a connection. Expected result * 2 is obtained. * @expect 1. The connection is successfully established. * 2. Session restoration fails. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC008(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; HLT_FD sockFd2 = {0}; int cunt = 1; int32_t serverConfigId = 0; int32_t serverConfigId2 = 0; HITLS_Session *session = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_Ctx_Config *serverCtxConfig2 = HLT_NewCtxConfig(NULL, "SERVER"); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); serverConfigId2 = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); serverConfigId2 = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // 2. Apply for another server that does not support the extension and establish a connection. HLT_SetExtenedMasterSecretSupport(serverCtxConfig2, false); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (session != NULL) { DataChannelParam channelParam2; channelParam2.port = g_uiPort; channelParam2.type = connType; channelParam2.isBlock = true; sockFd2 = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam2); ASSERT_TRUE((sockFd2.srcFd > 0) && (sockFd2.peerFd > 0)); remoteProcess->connFd = sockFd2.peerFd; localProcess->connFd = sockFd2.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId2 = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId2); HLT_Ssl_Config *serverSslConfig2; serverSslConfig2 = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig2 != NULL); serverSslConfig2->sockFd = remoteProcess->connFd; serverSslConfig2->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId2, serverSslConfig2) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId2); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); ASSERT_TRUE(HLT_TlsConnect(clientSsl) != 0); } else { DataChannelParam channelParam; channelParam.port = g_uiPort; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); cunt++; } while (cunt <= 2); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ static void Test_ClientHelloWithnoEMS(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS12; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS12; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->extendedMasterSecret.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC009 * @title Resume sessions that both support no EMS on the client and server * @precon nan * @brief 1. The client and server that does not support the extension connection establishment. * Disconnect the connection and save the session. * 2. Apply for another server that does not support the extension and establish a connection. Expected result * 2 is obtained. * @expect 1. The connection is successfully established. * 2. Session restoration success. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC7627_CONSISTENCY_EXTENDED_MASTER_SECRET_FUNC_TC009(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; int32_t cnt = 1; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_SetExtenedMasterSecretSupport(clientCtxConfig, false); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_SetExtenedMasterSecretSupport(serverCtxConfig, false); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (session != NULL) { ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); } else { RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHelloWithnoEMS}; RegisterWrapper(wrapper); } DataChannelParam channelParam; channelParam.port = g_uiPort; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); uint8_t isReused = 0; ASSERT_TRUE(HITLS_IsSessionReused(clientSsl, &isReused) == HITLS_SUCCESS); ASSERT_TRUE(isReused != 0); } else { ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_RpcTlsClose(remoteProcess, serverSslId) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); } cnt++; } while (cnt < 3); EXIT: ClearWrapper(); HLT_CleanFrameHandle(); HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_hlt_tls12_consistency_rfc7627.c
C
unknown
25,918
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls12_consistency_rfc5246 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "securec.h" #include "conn_init.h" /* END_HEADER */ #define g_uiPort 12121 /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_ECDHE_ECDSA_FUNC_TC001 * @title ECDHE_ECDSA requires an ECDSA certificate * @precon nan * @brief Set the cipher suite to ECDHE_ECDSA and the certificate to ECDSA. The expected connection setup success is * expected. * @expect 1. A success message is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_ECDHE_ECDSA_FUNC_TC001(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); TestSetCertPath(serverCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); HLT_SetClientVerifySupport(serverCtxConfig, true); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); // Set the cipher suite to ECDHE_ECDSA and the certificate to ECDSA. TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1"); HLT_SetClientVerifySupport(clientCtxConfig, true); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_ECDHE_ECDSA_FUNC_TC002 * @title ECDHE_ECDSA requires an ECDSA certificate * @precon nan * @brief Set the algorithm set to ECDHE_ECDSA and the certificate to the RSA certificate, Expected chain building * failure * @expect 1. A failure message is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_ECDHE_ECDSA_FUNC_TC002(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); TestSetCertPath(serverCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); HLT_SetClientVerifySupport(serverCtxConfig, true); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); // Set the algorithm set to ECDHE_ECDSA and the certificate to the RSA certificate, TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1"); HLT_SetClientVerifySupport(clientCtxConfig, true); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_CURVE_AND_AUTH_FUNC_TC001 * @title When the server selects the ECC cipher suite, the extension of the client must be considered for key exchange and certificate. * @precon nan * @brief 1. Set the curve secp256r1 and secp384r1 on the client and server, set the certificate curve secp384r1 on * the server, and set the ECC cipher suite. It is expected that the certificate is loaded successfully. * Set serverkeyexchange to secp256r1, and the connection is set up successfully. * @expect 1. The connection is set up successfully. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_CURVE_AND_AUTH_FUNC_TC001(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); TestSetCertPath(serverCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384"); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1:HITLS_EC_GROUP_SECP384R1"); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384"); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientCtxConfig, NULL); /* 1. Set the curve secp256r1 and secp384r1 on the client and server, set the certificate curve secp384r1 on * the server, and set the ECC cipher suite. It is expected that the certificate is loaded successfully. * Set serverkeyexchange to secp256r1 */ int ret = HLT_TlsConnect(clientRes->ssl); ASSERT_TRUE(ret == 0); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_CURVE_AND_AUTH_FUNC_TC002 * @spec - * @title When the server selects the ECC cipher suite, both the key exchange and certificate must comply with the * extension of the client. * @precon nan * @brief 1. Set the curve secp256r1 on the client and server, set the certificate curve secp384r1, and set the ECC * cipher suite. The certificate is loaded successfully. * Set the serverkeyexchange parameter is set to secp256r1, the connection fails to be established. * @expect 1. Connect establishment fails. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_CURVE_AND_AUTH_FUNC_TC002(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); TestSetCertPath(serverCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384"); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1"); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384"); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientCtxConfig, NULL); /* Set the curve secp256r1 on the client and server, set the certificate curve secp384r1, and set the ECC * cipher suite. */ int ret = HLT_TlsConnect(clientRes->ssl); ASSERT_TRUE(ret != 0); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); } /* END_CASE */ static void Test_SetCipherSuites_With_Link(CipherInfo serverCipher, CipherInfo clientCipher, bool expectSuccess) { int ret; HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *client_remote = NULL; HLT_Process *server_local = NULL; server_local = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(server_local != NULL); client_remote = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, false); ASSERT_TRUE(client_remote != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetCipherSuites(serverCtxConfig, serverCipher.cipher); HLT_SetGroups(serverCtxConfig, serverCipher.groups); HLT_SetSignature(serverCtxConfig, serverCipher.signAlg); TestSetCertPath(serverCtxConfig, serverCipher.signAlg); serverRes = HLT_ProcessTlsAccept(server_local, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCipherSuites(clientCtxConfig, clientCipher.cipher); HLT_SetGroups(clientCtxConfig, clientCipher.groups); HLT_SetSignature(clientCtxConfig, clientCipher.signAlg); TestSetCertPath(clientCtxConfig, clientCipher.signAlg); clientRes = HLT_ProcessTlsConnect(client_remote, TLS1_2, clientCtxConfig, NULL); if (expectSuccess) { ASSERT_TRUE(clientRes != NULL); } else { ASSERT_TRUE(clientRes == NULL); goto EXIT; } ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(server_local, serverRes, (uint8_t *)"Hello", strlen("Hello")) == 0); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; ret = HLT_ProcessTlsRead(client_remote, clientRes, readBuf, READ_BUF_SIZE, &readLen); ASSERT_TRUE(ret == 0); ASSERT_TRUE(readLen == strlen("Hello")); ASSERT_TRUE(memcmp("Hello", readBuf, readLen) == 0); EXIT: HLT_FreeAllProcess(); } /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC001 * @title One configuration, the configuration algorithm suite at both ends is the same, * and the negotiation behavior is verified * @precon nan * @brief 1. Set the cipher suite to HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 at both ends.Expected result 1 is obtained. * @expect 1. The negotiation is expected to succeed. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC001() { /* 1. Set the cipher suite to HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 at both ends. */ CipherInfo clientCipher = {.cipher = "HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", .groups = "HITLS_EC_GROUP_SECP384R1", .signAlg = "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", .cert = "rsa_sha256"}; CipherInfo serverCipher = {.cipher = "HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", .groups = "HITLS_EC_GROUP_SECP384R1", .signAlg = "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", .cert = "rsa_sha256"}; Test_SetCipherSuites_With_Link(serverCipher, clientCipher, true); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC002 * @title One configuration, the cipher suites configured at both ends are the same, and the negotiation behavior is * verified * @precon nan * @brief 1. Set the cipher suite to HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 at both ends. * Expected result 1 is obtained. * @expect 1. The negotiation is expected to succeed. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC002() { CipherInfo clientCipher = {.cipher = "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", .groups = "HITLS_EC_GROUP_SECP256R1", .signAlg = "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", .cert = "ecdsa_sha256"}; CipherInfo serverCipher = {.cipher = "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", .groups = "HITLS_EC_GROUP_SECP256R1", .signAlg = "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", .cert = "ecdsa_sha256"}; Test_SetCipherSuites_With_Link(serverCipher, clientCipher, true); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC003 * @title One configuration, the cipher suites configured at both ends are the same, and the negotiation behavior is * verified. * @precon nan * @brief 1. Set the cipher suite to HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA at both ends.Expected result 1 is obtained. * @expect 1. The negotiation is expected to succeed. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC003() { // 1. Set the cipher suite to HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA at both ends. CipherInfo clientCipher = {.cipher = "HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", .groups = "HITLS_EC_GROUP_SECP256R1", .signAlg = "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", .cert = "ecdsa_sha256"}; CipherInfo serverCipher = {.cipher = "HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", .groups = "HITLS_EC_GROUP_SECP256R1", .signAlg = "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", .cert = "ecdsa_sha256"}; Test_SetCipherSuites_With_Link(serverCipher, clientCipher, true); } /* END_CASE */ /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC004 * @title One configuration,the cipher suites configured at both ends are the same, and the negotiation behavior is * verified. * @precon nan * @brief 1. Set the cipher suite to HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA at both ends.Expected result 1 is obtained. * @expect 1. The negotiation is expected to succeed. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCY_SET_CIPHERSUITES_FUNC_TC004() { // 1. Set the cipher suite to HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA at both ends. CipherInfo clientCipher = {.cipher = "HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", .groups = "HITLS_EC_GROUP_SECP256R1", .signAlg = "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", .cert = "rsa_sha256"}; CipherInfo serverCipher = {.cipher = "HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", .groups = "HITLS_EC_GROUP_SECP256R1", .signAlg = "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", .cert = "rsa_sha256"}; Test_SetCipherSuites_With_Link(serverCipher, clientCipher, true); } /* END_CASE */ static void MalformedClientHelloMsgCallback(void *msg, void *userData) { // 2. Obtain the message, modify the field content, and send the message. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->pointFormats.exDataLen.data = 1; clientHello->pointFormats.exData.state = MISSING_FIELD; EXIT: return; } /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCYECDHE_ERR_POINT_FUNC_TC001 * @title Set the ECC cipher suite.Before the server receives the client hello message, the extended value of the * point format is changed to 1. As a result, the negotiation on the server is expected to fail. * @precon nan * @brief 1. The tested end functions as the client, and the tested end functions as the server.Expected result 1 is * obtained. * 2. Obtain the message, modify the field content, and send the message.(Expected result 2) * 3. Check the status of the tested end.Expected result 3 is obtained. * 4. Check the status of the test end.Expected result 4 is obtained. * @expect 1. A success message is returned. * 2. A success message is returned . * 3. The tested end returns an alert message, and the status is alerted. * 4. The status of the test end is alerted, and the handshake status is ready to receive the serverHello * message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCYECDHE_ERR_POINT_FUNC_TC001(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; // 1. The tested end functions as the client, and the tested end functions as the server. handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedClientHelloMsgCallback; TestPara testPara = {0}; testPara.port = g_uiPort; // 4. Check the status of the test end. testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedServerHelloMsgCallback(void *msg, void *userData) { // 2. Obtain the message, modify the field content, and send the message. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ServerHelloMsg *serverHello = &frameMsg->body.hsMsg.body.serverHello; serverHello->pointFormats.exState = INITIAL_FIELD; serverHello->pointFormats.exType.state = INITIAL_FIELD; serverHello->pointFormats.exType.data = HS_EX_TYPE_POINT_FORMATS; uint8_t data[] = {0}; FRAME_ModifyMsgArray8(data, sizeof(data), &serverHello->pointFormats.exData, &serverHello->pointFormats.exDataLen); serverHello->pointFormats.exLen.state = INITIAL_FIELD; serverHello->pointFormats.exLen.data = serverHello->pointFormats.exDataLen.data + sizeof(uint8_t); serverHello->pointFormats.exDataLen.data = 1; serverHello->pointFormats.exData.state = MISSING_FIELD; EXIT: return; } /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCYECDHE_ERR_POINT_FUNC_TC002 * @title uses the ECC cipher suite.During connection setup, the serverhello message carries the point format and the * point format is set to 1. The connection setup fails. * @precon nan * @brief 1. The tested end functions as the server and the tested end functions as the client.Expected result 1 is * obtained. * 2. Obtain the message, modify the field content, and send the message.(Expected result 2) * 3. Check the status of the tested end.Expected result 3 is obtained. * 4. Check the status of the test end.Expected result 4 is obtained. * @expect 1. A success message is returned. * 2. A success message is returned * 3. The tested end returns an alert message, indicating that the status is alerted. * 4. The status of the tested end is alerted. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCYECDHE_ERR_POINT_FUNC_TC002(void) { HLT_FrameHandle handle = {0}; handle.userData = (void *)&handle; handle.pointType = POINT_SEND; handle.expectReType = REC_TYPE_HANDSHAKE; // 1. The tested end functions as the server and the tested end functions as the client. handle.expectHsType = SERVER_HELLO; handle.frameCallBack = MalformedServerHelloMsgCallback; TestPara testPara = {0}; testPara.port = g_uiPort; testPara.isSupportExtendMasterSecret = true; // 4. The status of the tested end is alerted. testPara.expectHsState = TRY_RECV_CLIENT_KEY_EXCHANGE; // 3. Check the status of the tested end. testPara.expectDescription = ALERT_DECODE_ERROR; ServerSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */ static void MalformedNoCurveExternsionCallback(void *msg, void *userData) { // 2. Modify the client to send a client hello message and remove the elliptic curve extension. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ClientHelloMsg *clientHello = &frameMsg->body.hsMsg.body.clientHello; clientHello->supportedGroups.exState = MISSING_FIELD; clientHello->supportedGroups.exData.state = MISSING_FIELD; clientHello->supportedGroups.exDataLen.state = MISSING_FIELD; clientHello->supportedGroups.exLen.state = MISSING_FIELD; clientHello->supportedGroups.exType.state = MISSING_FIELD; EXIT: return; } /** @ * @test SDV_TLS_TLS12_RFC8422_CONSISTENCYECDHE_ECDHE_LOSE_CURVE_FUNC_TC001 * @title: Configure the ECC cipher suite and remove the elliptic curve extension before the server receives the client * hello message.As a result,the connection establishment fails. * @precon nan * @brief 1. The server stops receiving client Hello messages.Expected result 1 is obtained * 2. Modify the client to send a client hello message and remove the elliptic curve extension.Expected result * 2 is obtained. * 3. The server continues to establish a connection.(Expected result 3) * @expect 1. Success * 2. Success * 3. A decryption failure message is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS12_RFC8422_CONSISTENCYECDHE_ECDHE_LOSE_CURVE_FUNC_TC001(void) { HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; // 1. The server stops receiving client Hello messages. handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = MalformedNoCurveExternsionCallback; TestPara testPara = {0}; testPara.port = g_uiPort; testPara.isSupportExtendMasterSecret = true; testPara.expectHsState = TRY_RECV_SERVER_HELLO; // 3. The server continues to establish a connection. testPara.expectDescription = ALERT_HANDSHAKE_FAILURE; ClientSendMalformedRecordHeaderMsg(&handle, &testPara); return; } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls12/test_suite_sdv_hlt_tls12_consistency_rfc8422.c
C
unknown
23,303
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <unistd.h> #include "securec.h" #include "bsl_sal.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "tls.h" #include "hs.h" #include "hs_ctx.h" #include "hs_state_recv.h" #include "conn_init.h" #include "app.h" #include "alert.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "recv_process.h" #include "stub_replace.h" #include "frame_tls.h" #include "frame_msg.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "frame_io.h" #include "frame_link.h" #include "cert.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "hlt.h" #include "sctp_channel.h" #include "logger.h" #include "alert.h" #include "stub_crypt.h" #include "rec_wrapper.h" #define PARSEMSGHEADER_LEN 13 /* Message header length */ #define ILLEGAL_VALUE 0xFF /* Invalid value */ #define HASH_EXDATA_LEN_ERROR 23 /* Length of the content of the client_HELLOW signature hash field */ #define SIGNATURE_ALGORITHMS 0x04, 0x03 /* Fields added to the SERVER_HELLOW message */ #define READ_BUF_SIZE (18 * 1024) /* Maximum length of the read message buffer */ #define READ_BUF_LEN_18K (18 * 1024) #define TEMP_DATA_LEN 1024 /* Length of a single message */ #define ALERT_BODY_LEN 2u /* Alert data length */ #define GetEpochSeq(epoch, seq) (((uint64_t)(epoch) << 48) | (seq)) typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; bool isServerExtendMasterSecret; bool isSupportRenegotiation; /* Renegotiation support flag */ bool needStopBeforeRecvCCS; /* CCS test, so that the TRY_RECV_FINISH stops before the CCS message is received */ } HandshakeTestInfo; typedef struct { char *cipher; char *groups; char *signAlg; char *cert; } CipherInfo; typedef struct { int port; HITLS_HandshakeState expectHsState; // Expected Local Handshake Status. bool alertRecvFlag; // Indicates whether the alert is received. The value fasle indicates the sent alert, and the value true indicates the received alert. ALERT_Description expectDescription; // Expected alert description of the test end. bool isSupportClientVerify; // Indicates whether to use the dual-end verification. bool isSupportExtendMasterSecret; // Indicates whether to use an extended master key. bool isSupportDhCipherSuites; // Indicates whether to use the DHE cipher suite bool isExpectRet; // Indicates whether the return value is expected. int expectRet; // Expected return value. The isExpectRet function needs to be enabled. const char *serverGroup; // Configure the group supported by the server. If this parameter is not specified, the default value is used. const char *serverSignature; // Configure the signature algorithm supported by the server. If this parameter is left empty, the default value is used. const char *clientGroup; // Configure the group supported by the client. If this parameter is left empty, the default value is used. const char *clientSignature; // Configure the signature algorithm supported by the client. If this parameter is left empty, the default value is used. } TestPara; int32_t StatusPark(HandshakeTestInfo *testInfo) { /** Construct link */ testInfo->client = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } /* Perform the CCS test so that the TRY_RECV_FINISH is stopped before the CCS message is received. * The default value is False, which does not affect the original test. */ testInfo->client->needStopBeforeRecvCCS = testInfo->isClient ? testInfo->needStopBeforeRecvCCS : false; testInfo->server->needStopBeforeRecvCCS = testInfo->isClient ? false : testInfo->needStopBeforeRecvCCS; /** Establish a link and stop in a certain state. */ if (FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t DefaultCfgStatusPark(HandshakeTestInfo *testInfo) { FRAME_Init(); /** Construct configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; testInfo->config->isSupportRenegotiation = testInfo->isSupportRenegotiation; return StatusPark(testInfo); } int32_t DefaultCfgStatusParkWithSuite(HandshakeTestInfo *testInfo) { FRAME_Init(); /** Construct configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(testInfo->config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; return StatusPark(testInfo); } int32_t StatusPark1(HandshakeTestInfo *testInfo) { /* Construct a link. */ if(testInfo->isServerExtendMasterSecret == true){ testInfo->config->isSupportExtendMasterSecret = true; }else { testInfo->config->isSupportExtendMasterSecret = false; } testInfo->config->isSupportRenegotiation = false; testInfo->server = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } if(testInfo->isServerExtendMasterSecret == true){ testInfo->config->isSupportExtendMasterSecret = false; }else { testInfo->config->isSupportExtendMasterSecret = true; } testInfo->config->isSupportRenegotiation = testInfo->isSupportRenegotiation; testInfo->client = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } /* Set up a link and stop in a certain state. */ if (FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t DefaultCfgStatusPark1(HandshakeTestInfo *testInfo) { FRAME_Init(); /* Construct the configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t groups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo->config, groups, sizeof(groups) / sizeof(uint16_t)); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(testInfo->config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; return StatusPark1(testInfo); } int32_t StatusPark2(HandshakeTestInfo *testInfo) { /* Construct a link. */ testInfo->client = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } /* Establish a link and stop in a certain state. */ if (FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t SendHelloReq(HITLS_Ctx *ctx) { /** Initialize the message buffer. */ uint8_t buf[HS_MSG_HEADER_SIZE] = {0u}; size_t len = HS_MSG_HEADER_SIZE; /** Write records. */ return REC_Write(ctx, REC_TYPE_HANDSHAKE, buf, len); } int32_t ConstructAnEmptyCertMsg(FRAME_LinkObj *link) { FRAME_Msg frameMsg = {0}; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(link->io); /** Obtain the message buffer. */ uint8_t *buffer = ioUserData->recMsg.msg; uint32_t len = ioUserData->recMsg.len; if (len == 0) { return HITLS_MEMCPY_FAIL; } /** Parse the message. */ uint32_t parseLen = 0; if (ParserTotalRecord(link, &frameMsg, buffer, len, &parseLen) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } /** Construct a message. */ CERT_Item *tmpCert = frameMsg.body.handshakeMsg.body.certificate.cert; frameMsg.body.handshakeMsg.body.certificate.cert = NULL; frameMsg.bodyLen = 15; /** reassemble */ if (PackFrameMsg(&frameMsg) != HITLS_SUCCESS) { frameMsg.body.handshakeMsg.body.certificate.cert = tmpCert; CleanRecordBody(&frameMsg); return HITLS_INTERNAL_EXCEPTION; } /** Message injection */ ioUserData->recMsg.len = 0; if (FRAME_TransportRecMsg(link->io, frameMsg.buffer, frameMsg.len) != HITLS_SUCCESS) { frameMsg.body.handshakeMsg.body.certificate.cert = tmpCert; CleanRecordBody(&frameMsg); return HITLS_INTERNAL_EXCEPTION; } frameMsg.body.handshakeMsg.body.certificate.cert = tmpCert; CleanRecordBody(&frameMsg); return HITLS_SUCCESS; } int32_t RandBytes(uint8_t *randNum, uint32_t randLen) { srand(time(0)); const int maxNum = 256u; for (uint32_t i = randLen - 1; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return HITLS_SUCCESS; } #define TEST_CLIENT_SEND_FAIL 1 uint32_t g_uiPort = 8889; void TestSetCertPath(HLT_Ctx_Config *ctxConfig, char *SignatureType) { if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA1", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA1")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA256")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, RSA_SHA256_PRIV_PATH3, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA384")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA384_EE_PATH, RSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA512", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA512")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA512_EE_PATH, RSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", strlen("CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA256_EE_PATH, ECDSA_SHA256_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", strlen("CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA384_EE_PATH, ECDSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", strlen("CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA512_EE_PATH, ECDSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SHA1", strlen("CERT_SIG_SCHEME_ECDSA_SHA1")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA1_CA_PATH, ECDSA_SHA1_CHAIN_PATH, ECDSA_SHA1_EE_PATH, ECDSA_SHA1_PRIV_PATH, "NULL", "NULL"); } } void ClientSendMalformedRecordHeaderMsg(HLT_FrameHandle *handle, TestPara *testPara) { // Create a process. HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, testPara->port, false); ASSERT_TRUE(remoteProcess != NULL); // The remote server listens on the TLS link. HLT_Ctx_Config *serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HLT_SetCipherSuites(serverConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetGroups(serverConfig, "HITLS_EC_GROUP_SECP256R1") == 0); ASSERT_TRUE(HLT_SetSignature(serverConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256") == 0); TestSetCertPath(serverConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, testPara->isSupportClientVerify) == 0); HLT_Tls_Res *serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Configure the TLS connection on the local client. HLT_Ctx_Config *clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(HLT_SetCipherSuites(clientConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetGroups(clientConfig, "HITLS_EC_GROUP_SECP256R1") == 0); ASSERT_TRUE(HLT_SetSignature(clientConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256") == 0); TestSetCertPath(clientConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); HLT_Tls_Res *clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); // Configure the interface for constructing abnormal messages. handle->ctx = clientRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Set up a link and wait for the local end to complete the link. ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) != 0); // Wait the remote end. ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) != 0); // Confirm the final status. ASSERT_EQ(HLT_RpcTlsGetStatus(remoteProcess, serverRes->sslId), CM_STATE_ALERTED); ASSERT_EQ((ALERT_Level)HLT_RpcTlsGetAlertLevel(remoteProcess, serverRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ((ALERT_Description)HLT_RpcTlsGetAlertDescription(remoteProcess, serverRes->sslId), testPara->expectDescription); ASSERT_EQ(((HITLS_Ctx *)(clientRes->ssl))->hsCtx->state, testPara->expectHsState); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void ServerSendMalformedRecordHeaderMsg(HLT_FrameHandle *handle, TestPara *testPara) { // Create a process. HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, testPara->port, true); ASSERT_TRUE(remoteProcess != NULL); // The local server listens on the TLS link. HLT_Ctx_Config *serverConfig1 = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig1 != NULL); ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig1, testPara->isSupportClientVerify) == 0); ASSERT_TRUE(HLT_SetCipherSuites(serverConfig1, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetGroups(serverConfig1, "HITLS_EC_GROUP_SECP256R1") == 0); ASSERT_TRUE(HLT_SetSignature(serverConfig1, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256") == 0); TestSetCertPath(serverConfig1, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); HLT_Tls_Res *serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverConfig1, NULL); ASSERT_TRUE(serverRes != NULL); // Configure the interface for constructing abnormal messages. handle->ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Set up a TLS link on the remote client. HLT_Ctx_Config *clientConfig1 = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig1 != NULL); ASSERT_TRUE(HLT_SetCipherSuites(clientConfig1, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetGroups(clientConfig1, "HITLS_EC_GROUP_SECP256R1") == 0); ASSERT_TRUE(HLT_SetSignature(clientConfig1, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256") == 0); TestSetCertPath(clientConfig1, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); HLT_Tls_Res *clientRes = HLT_ProcessTlsInit(remoteProcess, TLS1_2, clientConfig1, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId) != 0); // Wait for the local end. ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) != 0); // Confirm the final status. ASSERT_EQ(((HITLS_Ctx *)(serverRes->ssl))->hsCtx->state, testPara->expectHsState); ASSERT_TRUE(HLT_RpcTlsGetStatus(remoteProcess, clientRes->sslId) == CM_STATE_ALERTED); ASSERT_EQ((ALERT_Level)HLT_RpcTlsGetAlertLevel(remoteProcess, clientRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ((ALERT_Description)HLT_RpcTlsGetAlertDescription(remoteProcess, clientRes->sslId), testPara->expectDescription); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void SetFrameType(FRAME_Type *frametype, uint16_t versionType, REC_Type recordType, HS_MsgType handshakeType, HITLS_KeyExchAlgo keyExType) { frametype->versionType = versionType; frametype->recordType = recordType; frametype->handshakeType = handshakeType; frametype->keyExType = keyExType; frametype->transportType = BSL_UIO_TCP; }
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls12/test_suite_tls12_consistency_rfc5246.base.c
C
unknown
20,219
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <semaphore.h> #include "securec.h" #include "hitls_error.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "simulate_io.h" #include "tls.h" #include "hs_ctx.h" #include "hlt.h" #include "alert.h" #include "record.h" #include "bsl_uio.h" #include "hitls.h" #include "pack_frame_msg.h" #include "parser_frame_msg.h" #define MAX_SESSION_ID_SIZE TLS_HS_MAX_SESSION_ID_SIZE #define MIN_SESSION_ID_SIZE TLS_HS_MIN_SESSION_ID_SIZE #define COOKIE_SIZE 32u #define DN_SIZE 32u #define EXTRA_DATA_SIZE 12u #define PORT 8005 // The SDV test is a parallel test. The port number used by each test suite must be unique. // for sni int32_t ServernameCbErrOK(HITLS_Ctx *ctx, int *alert, void *arg) { (void)ctx; (void)alert; (void)arg; return HITLS_ACCEPT_SNI_ERR_OK; } // end for sni // for alpn #define MAX_PROTOCOL_LEN 65536 /* Protocol matching function at the application layer */ static int32_t ExampleAlpnSelectProtocol(uint8_t **out, uint8_t *outLen, uint8_t *clientAlpnList, uint8_t clientAlpnListLen, uint8_t *servAlpnList, uint8_t servAlpnListLen) { int32_t ret = HITLS_ALPN_ERR_ALERT_FATAL; if (out == NULL || outLen == NULL || clientAlpnList == NULL || servAlpnList == NULL) { return HITLS_NULL_INPUT; } uint8_t i = 0; uint8_t j = 0; for (i = 0; i < servAlpnListLen;) { for (j = 0; j < clientAlpnListLen;) { if (servAlpnList[i] == clientAlpnList[j] && (memcmp(&servAlpnList[i + 1], &clientAlpnList[j + 1], servAlpnList[i]) == 0)) { *out = &servAlpnList[i + 1]; *outLen = servAlpnList[i]; ret = HITLS_ALPN_ERR_OK; goto EXIT; } j = j + clientAlpnList[j]; ++j; } i = i + servAlpnList[i]; ++i; } EXIT: return ret; } /* UserData structure transferred by the server to the alpnCb callback. */ typedef struct TlsAlpnExtCtx_ { uint8_t *serverAlpnList; uint32_t serverAlpnListLen; } TlsAlpnExtCtx; /* Select callback for the alpn on the server. */ int32_t ExampleAlpnCbForLlt(HITLS_Ctx *ctx, uint8_t **selectedProto, uint8_t *selectedProtoSize, uint8_t *clientAlpnList, uint32_t clientAlpnListSize, void *userData) { (void)ctx; int32_t ret = 0u; TlsAlpnExtCtx *alpnData = (TlsAlpnExtCtx *)userData; uint8_t *selected = NULL; uint8_t selectedLen = 0u; ret = ExampleAlpnSelectProtocol(&selected, &selectedLen, clientAlpnList, clientAlpnListSize, alpnData->serverAlpnList, alpnData->serverAlpnListLen); if (ret != HITLS_ALPN_ERR_OK) { return ret; } *selectedProto = selected; *selectedProtoSize = selectedLen; return HITLS_SUCCESS; } /* Parse the comma-separated application layer protocols transferred by the executable function. */ int32_t ExampleAlpnParseProtocolList(uint8_t *out, uint32_t *outLen, uint8_t *in, uint32_t inLen) { if (out == NULL || outLen == NULL || in == NULL) { return HITLS_NULL_INPUT; } if (inLen == 0 || inLen > MAX_PROTOCOL_LEN) { return HITLS_CONFIG_INVALID_LENGTH; } uint32_t i = 0u; uint32_t commaNum = 0u; uint32_t startPos = 0u; for (i = 0u; i <= inLen; ++i) { if (i == inLen || in[i] == ',') { if (i == startPos) { ++startPos; ++commaNum; continue; } out[startPos - commaNum] = (uint8_t)(i - startPos); startPos = i + 1; } else { out[i + 1 - commaNum] = in[i]; } } *outLen = inLen + 1 - commaNum; return HITLS_SUCCESS; } int32_t ExampleAlpnParseProtocolList2(uint8_t *out, uint32_t *outLen, uint8_t *in, uint32_t inLen) { if (out == NULL || outLen == NULL || in == NULL) { return HITLS_NULL_INPUT; } if (inLen == 0 || inLen > MAX_PROTOCOL_LEN) { return HITLS_CONFIG_INVALID_LENGTH; } uint32_t i = 0u; uint32_t commaNum = 0u; uint32_t startPos = 0u; for (i = 0u; i <= inLen; ++i) { if (i == inLen || in[i] == ',') { if (i == startPos) { ++startPos; ++commaNum; continue; } out[startPos - commaNum] = (uint8_t)(i - startPos); startPos = i + 1; } else { out[i + 1 - commaNum] = in[i]; } } *outLen = inLen + 1 - commaNum; return HITLS_SUCCESS; } // end for alpn typedef struct { int port; HITLS_HandshakeState expectHsState; bool alertRecvFlag; ALERT_Description expectDescription; bool isSupportClientVerify; bool isSupportExtendMasterSecret; bool isSupportSni; bool isSupportALPN; bool isSupportDhCipherSuites; bool isSupportSessionTicket; bool isExpectRet; int expectRet; const char *serverGroup; const char *serverSignature; const char *clientGroup; const char *clientSignature; } TestPara; typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; bool isSupportRenegotiation; bool isSupportSessionTicket; bool needStopBeforeRecvCCS; } HandshakeTestInfo; int32_t StatusPark(HandshakeTestInfo *testInfo) { testInfo->client = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } /* CCS test, so that the TRY_RECV_FINISH is stopped before the CCS packet is received. * The default value is False, which does not affect the original test. */ testInfo->client->needStopBeforeRecvCCS = testInfo->isClient ? testInfo->needStopBeforeRecvCCS : false; testInfo->server->needStopBeforeRecvCCS = testInfo->isClient ? false : testInfo->needStopBeforeRecvCCS; /** Set up a connection and stop in a certain state. */ if (FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t DefaultCfgStatusPark(HandshakeTestInfo *testInfo) { FRAME_Init(); /* Construct the configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t groups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo->config, groups, sizeof(groups) / sizeof(uint16_t)); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(testInfo->config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; testInfo->config->isSupportSessionTicket = testInfo->isSupportSessionTicket; return StatusPark(testInfo); } /* The local server initiates a connection creation request: Ignore whether the link creation is successful.*/ void ServerAccept(HLT_FrameHandle *handle, TestPara *testPara) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; // Create a process. localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, testPara->port, true); ASSERT_TRUE(remoteProcess != NULL); // The local server listens on the TLS connection. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, testPara->isSupportClientVerify) == 0); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Configure the interface for constructing abnormal messages. handle->ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Set up a TLS connection on the remote client. clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(HLT_SetExtenedMasterSecretSupport(clientConfig, testPara->isSupportExtendMasterSecret) == 0); clientRes = HLT_ProcessTlsInit(remoteProcess, TLS1_2, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); HLT_RpcTlsConnect(remoteProcess, clientRes->sslId); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void ServerSendMalformedRecordHeaderMsg(HLT_FrameHandle *handle, TestPara *testPara) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; // Create a process. localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, testPara->port, true); ASSERT_TRUE(remoteProcess != NULL); // The local server listens on the TLS link. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, testPara->isSupportClientVerify) == 0); ASSERT_TRUE(HLT_SetSessionTicketSupport(serverConfig, testPara->isSupportSessionTicket) == 0); if (testPara->isSupportDhCipherSuites) { ASSERT_TRUE(HLT_SetCipherSuites(serverConfig, "HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetSignature(serverConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256") == 0); HLT_SetCertPath( serverConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } if (testPara->serverGroup != NULL) { ASSERT_TRUE(HLT_SetGroups(serverConfig, testPara->serverGroup) == 0); } if (testPara->serverSignature != NULL) { ASSERT_TRUE(HLT_SetSignature(serverConfig, testPara->serverSignature) == 0); } serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Configure the interface for constructing abnormal messages. handle->ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Set up a TLS connection on the remote client. clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(HLT_SetExtenedMasterSecretSupport(clientConfig, testPara->isSupportExtendMasterSecret) == 0); ASSERT_TRUE(HLT_SetSessionTicketSupport(clientConfig, testPara->isSupportSessionTicket) == 0); if (testPara->isSupportDhCipherSuites) { ASSERT_TRUE(HLT_SetCipherSuites(clientConfig, "HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetSignature(clientConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256") == 0); HLT_SetCertPath( clientConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } if (testPara->clientGroup != NULL) { ASSERT_TRUE(HLT_SetGroups(clientConfig, testPara->clientGroup) == 0); } if (testPara->clientSignature != NULL) { ASSERT_TRUE(HLT_SetSignature(clientConfig, testPara->clientSignature) == 0); } clientRes = HLT_ProcessTlsInit(remoteProcess, TLS1_2, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); if (testPara->isExpectRet) { ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), testPara->expectRet); } else { ASSERT_TRUE(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId) != 0); } // Wait for the local. ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); // Confirm the final status. ASSERT_TRUE(((HITLS_Ctx *)(serverRes->ssl))->state == CM_STATE_ALERTED); ASSERT_TRUE(((HITLS_Ctx *)(serverRes->ssl))->hsCtx != NULL); ASSERT_EQ(((HITLS_Ctx *)(serverRes->ssl))->hsCtx->state, testPara->expectHsState); ASSERT_TRUE(HLT_RpcTlsGetStatus(remoteProcess, clientRes->sslId) == CM_STATE_ALERTED); if (testPara->alertRecvFlag) { ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, clientRes->sslId), ALERT_FLAG_RECV); } else { ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, clientRes->sslId), ALERT_FLAG_SEND); } ASSERT_EQ((ALERT_Level)HLT_RpcTlsGetAlertLevel(remoteProcess, clientRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ( (ALERT_Description)HLT_RpcTlsGetAlertDescription(remoteProcess, clientRes->sslId), testPara->expectDescription); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void ClientSendMalformedRecordHeaderMsg(HLT_FrameHandle *handle, TestPara *testPara) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; // Create a process. localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, testPara->port, false); ASSERT_TRUE(remoteProcess != NULL); // The remote server listens on the TLS connection. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HLT_SetSessionTicketSupport(serverConfig, testPara->isSupportSessionTicket) == 0); if (testPara->isSupportSni) { ASSERT_TRUE(HLT_SetServerNameCb(serverConfig, "ExampleSNIArg") == 0); ASSERT_TRUE(HLT_SetServerNameArg(serverConfig, "ExampleSNIArg") == 0); } if (testPara->isSupportALPN) { ASSERT_TRUE(HLT_SetAlpnProtosSelectCb(serverConfig, "ExampleAlpnCb", "ExampleAlpnData") == 0); } if (testPara->isSupportDhCipherSuites) { ASSERT_TRUE(HLT_SetCipherSuites(serverConfig, "HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetSignature(serverConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256") == 0); HLT_SetCertPath( serverConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } ASSERT_TRUE(HLT_SetClientVerifySupport(serverConfig, testPara->isSupportClientVerify) == 0); if (testPara->serverGroup != NULL) { ASSERT_TRUE(HLT_SetGroups(serverConfig, testPara->serverGroup) == 0); } if (testPara->serverSignature != NULL) { ASSERT_TRUE(HLT_SetSignature(serverConfig, testPara->serverSignature) == 0); } serverConfig->isSupportExtendMasterSecret = false; serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Configure the TLS connection on the local client. clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(HLT_SetSessionTicketSupport(clientConfig, testPara->isSupportSessionTicket) == 0); if (testPara->isSupportSni) { ASSERT_TRUE(HLT_SetServerNameCb(clientConfig, "testServer") == 0); } if (testPara->isSupportALPN) { static const char *alpn = "http,ftp"; uint8_t ParsedList[100] = {0}; uint32_t ParsedListLen; ExampleAlpnParseProtocolList2(ParsedList, &ParsedListLen, (uint8_t *)alpn, (uint32_t)strlen(alpn)); ASSERT_TRUE(HLT_SetAlpnProtos(clientConfig, (const char *)ParsedList) == 0); } if (testPara->isSupportDhCipherSuites) { ASSERT_TRUE(HLT_SetCipherSuites(clientConfig, "HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256") == 0); ASSERT_TRUE(HLT_SetSignature(clientConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256") == 0); HLT_SetCertPath( clientConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } if (testPara->clientGroup != NULL) { ASSERT_TRUE(HLT_SetGroups(clientConfig, testPara->clientGroup) == 0); } if (testPara->clientSignature != NULL) { ASSERT_TRUE(HLT_SetSignature(clientConfig, testPara->clientSignature) == 0); } ASSERT_TRUE(HLT_SetExtenedMasterSecretSupport(clientConfig, testPara->isSupportExtendMasterSecret) == 0); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); // Configure the interface for constructing abnormal messages. handle->ctx = clientRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Set up a connection and wait until the local is complete. ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) != 0); // Wait the remote. int ret = HLT_GetTlsAcceptResult(serverRes); ASSERT_TRUE(ret != 0); if (testPara->isExpectRet) { ASSERT_EQ(ret, testPara->expectRet); } // Final status confirmation ASSERT_EQ(HLT_RpcTlsGetStatus(remoteProcess, serverRes->sslId), CM_STATE_ALERTED); if (testPara->alertRecvFlag) { ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, serverRes->sslId), ALERT_FLAG_RECV); } else { ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, serverRes->sslId), ALERT_FLAG_SEND); } ASSERT_EQ((ALERT_Level)HLT_RpcTlsGetAlertLevel(remoteProcess, serverRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ( (ALERT_Description)HLT_RpcTlsGetAlertDescription(remoteProcess, serverRes->sslId), testPara->expectDescription); ASSERT_TRUE(((HITLS_Ctx *)(clientRes->ssl))->state == CM_STATE_ALERTED); ASSERT_TRUE(((HITLS_Ctx *)(clientRes->ssl))->hsCtx != NULL); ASSERT_EQ(((HITLS_Ctx *)(clientRes->ssl))->hsCtx->state, testPara->expectHsState); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } // for UT_TLS1_2_RFC5246_RECV_ZEROLENGTH_MSG_TC009 - UT_TLS1_2_RFC5246_RECV_ZEROLENGTH_MSG_TC010 int32_t g_writeRet; uint32_t g_writeLen; bool g_isUseWriteLen; uint8_t g_writeBuf[REC_DTLS_RECORD_HEADER_LEN + REC_MAX_CIPHER_TEXT_LEN]; int32_t STUB_MethodWrite(BSL_UIO *uio, const void *buf, uint32_t len, uint32_t *writeLen) { (void)uio; if (memcpy_s(g_writeBuf, sizeof(g_writeBuf), buf, len) != EOK) { return BSL_MEMCPY_FAIL; } *writeLen = len; if (g_isUseWriteLen) { *writeLen = g_writeLen; } return g_writeRet; } int32_t g_readRet; uint32_t g_readLen; uint8_t g_readBuf[REC_DTLS_RECORD_HEADER_LEN + REC_MAX_CIPHER_TEXT_LEN]; int32_t STUB_MethodRead(BSL_UIO *uio, void *buf, uint32_t len, uint32_t *readLen) { (void)uio; if (g_readLen != 0 && memcpy_s(buf, len, g_readBuf, g_readLen) != EOK) { return BSL_MEMCPY_FAIL; } *readLen = g_readLen; return g_readRet; } int32_t g_ctrlRet; BSL_UIO_CtrlParameter g_ctrlCmd; int32_t STUB_MethodCtrl(BSL_UIO *uio, int32_t cmd, int32_t larg, void *param) { (void)larg; (void)uio; (void)param; if ((int32_t)g_ctrlCmd == cmd) { return g_ctrlRet; } return BSL_SUCCESS; } HITLS_Config *g_tlsConfig = NULL; HITLS_Ctx *g_tlsCtx = NULL; BSL_UIO *g_uio = NULL; int32_t TlsCtxNew(BSL_UIO_TransportType type) { HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; BSL_UIO *uio = NULL; const BSL_UIO_Method *ori = NULL; switch (type) { case BSL_UIO_TCP: #ifdef HITLS_BSL_UIO_TCP ori = BSL_UIO_TcpMethod(); #endif break; default: #ifdef HITLS_BSL_UIO_SCTP ori = BSL_UIO_SctpMethod(); #endif break; } config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); BSL_UIO_Method method = {0}; memcpy(&method, ori, sizeof(method)); method.uioWrite = STUB_MethodWrite; method.uioRead = STUB_MethodRead; method.uioCtrl = STUB_MethodCtrl; uio = BSL_UIO_New(&method); ASSERT_TRUE(uio != NULL); ASSERT_TRUE(HITLS_SetUio(ctx, uio) == HITLS_SUCCESS); /* Default value of stub function */ g_writeRet = HITLS_SUCCESS; g_writeLen = 0; g_isUseWriteLen = false; g_readLen = 0; g_readRet = HITLS_SUCCESS; g_tlsConfig = config; g_tlsCtx = ctx; g_uio = uio; return HITLS_SUCCESS; EXIT: BSL_UIO_Free(uio); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); return HITLS_INTERNAL_EXCEPTION; } void TlsCtxFree(void) { BSL_UIO_Free(g_uio); HITLS_Free(g_tlsCtx); HITLS_CFG_FreeConfig(g_tlsConfig); g_uio = NULL; g_tlsCtx = NULL; g_tlsConfig = NULL; } // for UT_TLS1_2_RFC5246_RECV_ZEROLENGTH_MSG_TC009 - UT_TLS1_2_RFC5246_RECV_ZEROLENGTH_MSG_TC010 // for UT_TLS1_2_RFC5246_MISS_CLIENT_KEYEXCHANGE_TC001 #define PARSEMSGHEADER_LEN 13 #define ILLEGAL_VALUE 0xFF #define HASH_EXDATA_LEN_ERROR 23 /* Length of the CLIENT_HELLOW signature hash field. */ #define SIGNATURE_ALGORITHMS 0x04, 0x03 /* Field added to the end of the SERVER_HELLOW message */ #define READ_BUF_SIZE (18 * 1024) /* Maximum length of the read message buffer */ #define TEMP_DATA_LEN 1024 /* Length of a single packet. */ int32_t DefaultCfgStatusParkWithSuite(HandshakeTestInfo *testInfo) { FRAME_Init(); /** Construct the configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(testInfo->config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; return StatusPark(testInfo); } int32_t SendHelloReq(HITLS_Ctx *ctx) { uint8_t buf[HS_MSG_HEADER_SIZE] = {0u}; size_t len = HS_MSG_HEADER_SIZE; return REC_Write(ctx, REC_TYPE_HANDSHAKE, buf, len); } int32_t ConstructAnEmptyCertMsg(FRAME_LinkObj *link) { FRAME_Msg frameMsg = {0}; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(link->io); uint8_t *buffer = ioUserData->recMsg.msg; uint32_t len = ioUserData->recMsg.len; if (len == 0) { return HITLS_MEMCPY_FAIL; } /** Parse the message. */ uint32_t parseLen = 0; if (ParserTotalRecord(link, &frameMsg, buffer, len, &parseLen) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } /** Construct a message. */ CERT_Item *tmpCert = frameMsg.body.handshakeMsg.body.certificate.cert; frameMsg.body.handshakeMsg.body.certificate.cert = NULL; frameMsg.bodyLen = 15; if (PackFrameMsg(&frameMsg) != HITLS_SUCCESS) { frameMsg.body.handshakeMsg.body.certificate.cert = tmpCert; CleanRecordBody(&frameMsg); return HITLS_INTERNAL_EXCEPTION; } ioUserData->recMsg.len = 0; if (FRAME_TransportRecMsg(link->io, frameMsg.buffer, frameMsg.len) != HITLS_SUCCESS) { frameMsg.body.handshakeMsg.body.certificate.cert = tmpCert; CleanRecordBody(&frameMsg); return HITLS_INTERNAL_EXCEPTION; } frameMsg.body.handshakeMsg.body.certificate.cert = tmpCert; CleanRecordBody(&frameMsg); return HITLS_SUCCESS; } int32_t RandBytes(uint8_t *randNum, uint32_t randLen) { srand(time(0)); const int maxNum = 256u; for (uint32_t i = 0; i < randLen; i++) { randNum[i] = (uint8_t)(rand() % maxNum); } return HITLS_SUCCESS; } // for UT_TLS1_2_RFC5246_MISS_CLIENT_KEYEXCHANGE_TC001 // for UT_TLS1_2_RFC5246_CERTFICATE_VERITY_FAIL_TC006 - UT_TLS1_2_RFC5246_CERTFICATE_VERITY_FAIL_TC007 typedef struct { int connectExpect; // Expected connect result Return value on end C. int acceptExpect; // Expected accept result returned value on the s end. ALERT_Level expectLevel; // Expected alert level. ALERT_Description expectDescription; // Expected alert description of the tested end. } TestExpect; // Replace the sent message with ClientKeyExchange. void TEST_SendUnexpectClientKeyExchangeMsg(void *msg, void *data) { FRAME_Type *frameType = (FRAME_Type *)data; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; FRAME_Msg newFrameMsg = {0}; HS_MsgType hsTypeTmp = frameType->handshakeType; REC_Type recTypeTmp = frameType->recordType; frameType->handshakeType = CLIENT_KEY_EXCHANGE; FRAME_Init(); // Callback for changing the certificate algorithm, which is used to generate the negotiation // handshake message. FRAME_GetDefaultMsg(frameType, &newFrameMsg); HLT_TlsRegCallback(HITLS_CALLBACK_DEFAULT); // recovery callback FRAME_ModifyMsgInteger(frameMsg->epoch.data, &newFrameMsg.epoch); FRAME_ModifyMsgInteger(frameMsg->sequence.data, &newFrameMsg.sequence); FRAME_ModifyMsgInteger(frameMsg->body.hsMsg.sequence.data, &newFrameMsg.body.hsMsg.sequence); // Release the original msg. frameType->handshakeType = hsTypeTmp; frameType->recordType = recTypeTmp; FRAME_CleanMsg(frameType, frameMsg); // Change message. frameType->recordType = REC_TYPE_HANDSHAKE; frameType->handshakeType = CLIENT_KEY_EXCHANGE; frameType->keyExType = HITLS_KEY_EXCH_ECDHE; if (memcpy_s(msg, sizeof(FRAME_Msg), &newFrameMsg, sizeof(newFrameMsg)) != EOK) { Print("TEST_SendUnexpectClientKeyExchangeMsg memcpy_s Error!"); } } // Replace the message to be sent with the certificate. void TEST_SendUnexpectCertificateMsg(void *msg, void *data) { FRAME_Type *frameType = (FRAME_Type *)data; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; FRAME_Msg newFrameMsg = {0}; HS_MsgType hsTypeTmp = frameType->handshakeType; frameType->handshakeType = CERTIFICATE; /* Callback for changing the certificate algorithm, which is used to generate the negotiation handshake message. */ FRAME_Init(); FRAME_GetDefaultMsg(frameType, &newFrameMsg); HLT_TlsRegCallback(HITLS_CALLBACK_DEFAULT); // recovery callback // Release the original msg. frameType->handshakeType = hsTypeTmp; FRAME_CleanMsg(frameType, frameMsg); // Change message. frameType->recordType = REC_TYPE_HANDSHAKE; frameType->handshakeType = CERTIFICATE; frameType->keyExType = HITLS_KEY_EXCH_ECDHE; if (memcpy_s(msg, sizeof(FRAME_Msg), &newFrameMsg, sizeof(newFrameMsg)) != EOK) { Print("TEST_SendUnexpectCertificateMsg memcpy_s Error!"); } }
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls12/test_suite_tls12_consistency_rfc5246_malformed_msg.base.c
C
unknown
27,530
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "bsl_sal.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "securec.h" #include "rec_wrapper.h" #include "conn_init.h" #include "rec.h" #include "parse.h" #include "hs_msg.h" #include "hs.h" #include "alert.h" #include "hitls_type.h" #include "session_type.h" #include "hitls_crypt_init.h" #include "common_func.h" #include "hlt.h" #include "process.h" #include "rec_read.h" /* END_HEADER */ #define g_uiPort 6543 // REC_Read calls TlsRecordRead calls RecParseInnerPlaintext int32_t RecParseInnerPlaintext(TLS_Ctx *ctx, const uint8_t *text, uint32_t *textLen, uint8_t *recType); int32_t STUB_RecParseInnerPlaintext(TLS_Ctx *ctx, const uint8_t *text, uint32_t *textLen, uint8_t *recType) { (void)ctx; (void)text; (void)textLen; *recType = (uint8_t)REC_TYPE_APP; return HITLS_SUCCESS; } typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; } ResumeTestInfo; /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_APP_DATA_BEFORE_FINISH_FUNC_TC001 * @spec Application Data MUST NOT be sent prior to sending the Finished message * @brief 2.Protocol Overview row5 * 1. Initializing Configurations. * 2. Stay in the try finish state and send a message. * @expect * 1.Initialization succeeded. * 2.Return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_APP_DATA_BEFORE_FINISH_FUNC_TC001(int isClient) { FRAME_Init(); STUB_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); FRAME_LinkObj *sender = isClient ? client : server; FRAME_LinkObj *recver = isClient ? server : client; // During connection establishment, the client stops in the TRY_SEND_FINISH state. ASSERT_TRUE(FRAME_CreateConnection(sender, recver, true, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FuncStubInfo stubInfo = {0}; /* * Plaintext header of the wrapped record, which is of the app type for finish and app data. * After the wrapped record body is parsed (that is, the body is decrypted), the last nonzero byte of the body is * the actual record type. This case is constructed by tampering with the rec type to the app type, * which should be the hs type. */ STUB_Replace(&stubInfo, RecParseInnerPlaintext, STUB_RecParseInnerPlaintext); if (isClient) { ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); } else { ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&stubInfo); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NO_SUPPORTED_GROUP_FUNC_TC001 * @spec 1. Construct a scenario where the supported groups of the client and server do not overlap. Expect the server * to terminate the handshake and send a handshake_failure message after receiving the client hello message. * alert * @brief 4.1.1. Cryptographic Negotiation row 10 * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE. * */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NO_SUPPORTED_GROUP_FUNC_TC001() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS13Config(); HITLS_Config *config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); // Set the groups of the client uint16_t groups_c[] = {HITLS_EC_GROUP_SECP384R1}; uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384}; HITLS_CFG_SetGroups(config_c, groups_c, sizeof(groups_c) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); // Set the groups of the server uint16_t groups_s[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP521R1}; uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512}; HITLS_CFG_SetGroups(config_s, groups_s, sizeof(groups_s) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); bool isClient = true; int32_t ret = FRAME_CreateConnection(client, server, !isClient, TRY_RECV_CLIENT_HELLO); ASSERT_EQ(ret, HITLS_SUCCESS); ret = HITLS_Accept(server->ssl); ASSERT_EQ(ret, HITLS_MSG_HANDLE_HANDSHAKE_FAILURE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; FRAME_Msg parsedAlert = {0}; uint32_t parseLen; ASSERT_TRUE(FRAME_ParseTLSNonHsRecord(sndBuf, sndLen, &parsedAlert, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(parsedAlert.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedAlert.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_HANDSHAKE_FAILURE); EXIT: FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RSAE_PSS_FUNC_TC001 * @spec * The client signature algorithm is set to RSA_PSS_PSS_SHA256 and the server certificate signature algorithm * is set to RSA_PSS_RSAE_SHA256, the connection fails to be established. * @brief 4.2.3. Signature Algorithms row 54 * 1. Initialize configuration * 2. If the signature algorithms are inconsistent, the expected connection setup fails and * HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE is returned. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RSAE_PSS_FUNC_TC001() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS13Config(); HITLS_Config *config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); // The client signature algorithm is set to RSA_PSS_PSS_SHA256 uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256}; HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); // The server signature algorithm is set to RSA_PSS_RSAE_SHA256 uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256}; HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); FRAME_CertInfo certInfo = { "rsa_pss_sha256/rsa_pss_root.der", "rsa_pss_sha256/rsa_pss_intCa.der", "rsa_pss_sha256/rsa_pss_dev.der", 0, "rsa_pss_sha256/rsa_pss_dev.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RSAE_PSS_FUNC_TC002 * @spec - * The signature algorithm on the client is set to RSA_PSS_RSAE_SHA256 and the signature algorithm on the server * is set to RSA_PSS_PSS_SHA256, the connection fails to be established. * @brief 4.2.3. Signature Algorithms row 53 * 1. Initialize configuration * 2. If the signature algorithms are inconsistent, the expected connection setup fails and * HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE is returned. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RSAE_PSS_FUNC_TC002() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS13Config(); HITLS_Config *config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); // The signature algorithm on the client is set to RSA_PSS_RSAE_SHA256 uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256}; HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); // The signature algorithm on the server is set to RSA_PSS_PSS_SHA256 uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256}; HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); FRAME_CertInfo certInfo = { "rsa_pss_sha256/rsa_pss_root.der", "rsa_pss_sha256/rsa_pss_intCa.der", "rsa_pss_sha256/rsa_pss_dev.der", 0, "rsa_pss_sha256/rsa_pss_dev.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SIG_FUNC_TC001 * @brief 4.2.3. Signature Algorithms row 55 * 1. Set the client server to tls1.3 and the client signature algorithm to rsa-sha1. * 2. Set the client server to tls1.3 and the client signature algorithm to ecdsa-sha1. * 3. Set the client server to tls1.3 and the hash in the client signature algorithm to des-sha-224. The expected * connection establishment fails. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SIG_FUNC_TC001(int sig) { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS13Config(); HITLS_Config *config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t signAlgs_c[] = {(uint16_t)sig}; HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RSAE_SUPPORT_BY_TLS12SERVER_FUNC_TC001 * @brief 4.2.3. Signature Algorithms row 57 * 1. Initialize configuration * 2. Set the client to tls1.3, server to tls1.2, and the signature algorithm RSA_PSS_RSAE_SHA256 on the client. The * expected connection setup is successful. * @expect * 1.Initialization succeeded. * 2.The connection is successfully established. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RSAE_SUPPORT_BY_TLS12SERVER_FUNC_TC001() { FRAME_Init(); // tls 11, 12, 13 HITLS_Config *config_c = HITLS_CFG_NewTLSConfig(); HITLS_Config *config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); // 1. Set the client to tls1.3, server to tls1.2, and the signature algorithm RSA_PSS_RSAE_SHA256 on the client. uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256}; HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256}; HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); uint16_t cipherSuite[] = {HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(config_c, cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(config_s, cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)); FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_SESSID_FROM_SH_FUNC_TC001 * @spec legacy_session_id_echo: The contents of the client's * legacy_session_id field. Note that this field is echoed even if * the client' s value corresponded to a cached pre-TLS 1.3 session * which the server has chosen not to resume. A client which * receives a legacy_session_id_echo field that does not match what * it sent in the ClientHello MUST abort the handshake with an * "illegal_parameter" alert. * @brief 4.1.3. Server Hello row 25 * 1.Initialize configuration * 2.A client which receives a legacy_session_id_echo field that does not match what * it sent in the ClientHello MUST abort the handshake with an "illegal_parameter" alert. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_SESSID_FROM_SH_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg parsedSH = {0}; uint32_t parseLen = 0; FRAME_Type frameType = {0}; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &parsedSH, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *shMsg = &parsedSH.body.hsMsg.body.serverHello; memset_s((shMsg->sessionId.data), shMsg->sessionId.size, 1, shMsg->sessionId.size); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSH, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID); ALERT_Info alert = { 0 }; ALERT_GetInfo(client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: FRAME_CleanMsg(&frameType, &parsedSH); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_SESSID_FROM_SH_FUNC_TC002 * @spec legacy_session_id_echo: The contents of the client's * legacy_session_id field. Note that this field is echoed even if * the client' s value corresponded to a cached pre-TLS 1.3 session * which the server has chosen not to resume. A client which * receives a legacy_session_id_echo field that does not match what * it sent in the ClientHello MUST abort the handshake with an * "illegal_parameter" alert. * @brief 4.1.3. Server Hello row 25 * 1.Initialize configuration * 2.A client which receives a legacy_session_id_echo field that does not match what * it sent in the ClientHello MUST abort the handshake with an "illegal_parameter" alert. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_SESSID_FROM_SH_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg parsedSH = {0}; uint32_t parseLen = 0; FRAME_Type frameType = {0}; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &parsedSH, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *shMsg = &parsedSH.body.hsMsg.body.serverHello; shMsg->sessionId.size = 0; shMsg->sessionId.state = MISSING_FIELD; shMsg->sessionIdSize.data = 0; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSH, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID); ALERT_Info alert = { 0 }; ALERT_GetInfo(client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: FRAME_CleanMsg(&frameType, &parsedSH); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_CIPHERSUITE_FROM_SH_FUNC_TC001 * @spec serverSelect one of ClientHello.cipher_suites. If the server is not provided by the client, the client must * terminate the handshake and respond with an illegal message. parameter alarm row 26 * @brief cipher_suite: The single cipher suite selected by the server from * the list in ClientHello.cipher_suites. A client which receives a * cipher suite that was not offered MUST abort the handshake with an "illegal_parameter" alert. * 1.Initialize configuration * 2.A client which receives a cipher suite that was not offered MUST abort the handshake with an * "illegal_parameter" alert. * @expect * 1.Initialization succeeded. * 2.Return ALERT_ILLEGAL_PARAMETER. * */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_CIPHERSUITE_FROM_SH_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg parsedSH = {0}; uint32_t parseLen = 0; FRAME_Type frameType; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &parsedSH, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *shMsg = &parsedSH.body.hsMsg.body.serverHello; shMsg->cipherSuite.data = HITLS_AES_128_CCM_SHA256; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSH, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); FrameUioUserData *userData = BSL_UIO_GetUserData(client->io); uint8_t *alertBuf = userData->sndMsg.msg; uint32_t alertLen = userData->sndMsg.len; FRAME_Msg parsedAlert = {0}; uint32_t parsedAlertLen = 0; ASSERT_TRUE(FRAME_ParseTLSNonHsRecord(alertBuf, alertLen, &parsedAlert, &parsedAlertLen) == HITLS_SUCCESS); ASSERT_TRUE(parsedAlert.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedAlert.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_ILLEGAL_PARAMETER); EXIT: FRAME_CleanMsg(&frameType, &parsedSH); FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MISSING_SIG_ALG_FROM_CH_FUNC_TC001 * @spec * 1. Set the client server to tls1.3 and construct the client hello message that does not contain the * signature_algorithm extension. The server is expected to return the missing_extension alarm. * @brief If a server is authenticating via * a certificate and the client has not sent a "signature_algorithms" * extension, then the server MUST abort the handshake with a * "missing_extension" alert * 4.2.3. Signature Algorithms row 51 * 1.Initialize configuration * 2.A client which receives a cipher suite that was not offered MUST abort the handshake with an * "illegal_parameter" alert. * @expect * 1.Initialization succeeded. * 2.Return ALERT_MISSING_EXTENSION. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MISSING_SIG_ALG_FROM_CH_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg parsedCH = {0}; uint32_t parseLen = 0; FRAME_Type frameType = {0}; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &parsedCH, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *chMsg = &parsedCH.body.hsMsg.body.clientHello; chMsg->signatureAlgorithms.exState = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedCH, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_MSG_HANDLE_MISSING_EXTENSION); FrameUioUserData *userData = BSL_UIO_GetUserData(server->io); uint8_t *alertBuf = userData->sndMsg.msg; uint32_t alertLen = userData->sndMsg.len; FRAME_Msg parsedAlert = {0}; uint32_t parsedAlertLen = 0; ASSERT_TRUE(FRAME_ParseTLSNonHsRecord(alertBuf, alertLen, &parsedAlert, &parsedAlertLen) == HITLS_SUCCESS); ASSERT_TRUE(parsedAlert.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedAlert.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_MISSING_EXTENSION); EXIT: FRAME_CleanMsg(&frameType, &parsedCH); FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_CERT_VERIFY_FUNC_TC001 * @brief 4.4.3. Certificate Verify row 147 row 148 * 1. Set the signature algorithms on the client and server to CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, * Change the value of signature_algorithms in the CertificateVerify message sent by the server to * CERT_SIG_SCHEME_DSA_SHA224 and continue to establish a connection. Expected result: After receiving the * CertificateVerify message, the client sends an alert message and the connection is disconnected. * 2. Set the dual-end verification, set the signature algorithm supported by the client and server to * CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, and establish a connection, Change the signature algorithm field in * the CertificateVerify message sent by the client to CERT_SIG_SCHEME_DSA_SHA224. Expected result: * After receiving the CertificateVerify message, the server sends an alert message and the connection * is disconnected. * @expect * 1.The client sends an alert message and the connection is disconnected. * 2.The server sends an alert message and the connection is disconnected. * */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MODIFIED_CERT_VERIFY_FUNC_TC001(int isClient) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportClientVerify = true; FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); /* 1.Set the signature algorithms on the client and server to CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, * Change the value of signature_algorithms in the CertificateVerify message sent by the server to * CERT_SIG_SCHEME_DSA_SHA224 and continue to establish a connection. */ uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384}; HITLS_CFG_SetSignature(tlsConfig, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); ASSERT_TRUE(FRAME_CreateConnection(client, server, isClient, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); int32_t ret; HITLS_Ctx *ctx = isClient ? client->ssl : server->ssl; HS_Ctx *hsCtx = ctx->hsCtx; uint8_t *buf = hsCtx->msgBuf; uint32_t dataLen = 0; HS_MsgInfo hsMsgInfo = {0}; ret = REC_Read(ctx, REC_TYPE_HANDSHAKE, buf, &dataLen, hsCtx->bufferLen); ASSERT_TRUE(ret == HITLS_SUCCESS); /* 2. Set the dual-end verification, set the signature algorithm supported by the client and server to * CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, and establish a connection, Change the signature algorithm field in * the CertificateVerify message sent by the client to CERT_SIG_SCHEME_DSA_SHA224. */ memset_s(buf + HS_MSG_HEADER_SIZE, sizeof(uint16_t), CERT_SIG_SCHEME_DSA_SHA224, sizeof(uint16_t)); ret = HS_ParseMsgHeader(ctx, buf, dataLen, &hsMsgInfo); ASSERT_TRUE(ret == HITLS_SUCCESS); HS_Msg hsMsg = {0}; ret = HS_ParseMsg(ctx, &hsMsgInfo, &hsMsg); ASSERT_EQ(ret, HITLS_PARSE_UNSUPPORT_SIGN_ALG); ALERT_Info alertInfo = {0}; (void)ALERT_GetInfo(ctx, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_ILLEGAL_PARAMETER); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_TRUE(FRAME_CreateConnection(client, server, isClient, HS_STATE_BUTT) != HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMPTION_FUNC_TC001 * @brief */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMPTION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); HITLS_SetSession(client->ssl, clientSession); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FUNC_TC001 * @brief */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FUNC_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetPskServerCallback(config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); // 1.2 psk bind with sha256 uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; HITLS_CFG_SetGroups(config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PREFER_PSS_TO_PKCS1_FUNC_TC001 * @brief 4.4.3. Certificate Verify row 149 * 1.Initialize configuration * 2. Configure the RSA certificate on the server and set the signature algorithm supported by the server to * {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256}, Establish a connection and check whether * the negotiated signature algorithm is CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256. Expected result: * CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256 is negotiated. * @expect * 1.Initialization succeeded. * 2.The connection is successfully set up, and the negotiation algorithm is CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PREFER_PSS_TO_PKCS1_FUNC_TC001() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS13Config(); HITLS_Config *config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256}; HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); uint16_t cipherSuite[] = {HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(config_s, cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)); FRAME_CertInfo certInfo = { "rsa_pss_sha256/rsa_pss_root.der", "rsa_pss_sha256/rsa_pss_intCa.der", "rsa_pss_sha256/rsa_pss_dev.der", 0, "rsa_pss_sha256/rsa_pss_dev.key.der", 0, }; FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfo); FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(server->ssl->negotiatedInfo.signScheme, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyFinish(HITLS_Ctx *ctx, uint8_t *buf, uint32_t *bufLen, uint32_t bufSize, void *userData) { (void)ctx; (void)userData; /* hs msg struct, the first byte indicates the HandshakeType, * the following 3 bytes indicate the remaining bytes in message */ uint8_t modifiedHsMsg[] = {KEY_UPDATE, 0, 0, sizeof(uint8_t), HITLS_UPDATE_REQUESTED}; (void)memcpy_s(buf, bufSize, modifiedHsMsg, sizeof(modifiedHsMsg)); *bufLen = sizeof(modifiedHsMsg); } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_INVALID_REQ_VAL_FUNC_TC001 * @brief 4.6.3. Key and Initialization Vector Update row 178 * 1. Establish a connection, change the value of the updata message sent by the client to 3, and observe the server * behavior. Expected result: The server returns the illegal parameter. * 2. Establish a connection, change the value of the updata message sent by the server to 3, and observe the client * behavior. Expected result: The client returns the illegal parameter. * @expect * 1.Initialization succeeded. * 2.Return ALERT_ILLEGAL_PARAMETER. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_INVALID_REQ_VAL_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); uint8_t data[] = {KEY_UPDATE, 0x00, 0x00, 0x01, 0x03}; ASSERT_TRUE(REC_Write(clientTlsCtx, REC_TYPE_HANDSHAKE, data, sizeof(data)) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); /* 1. Establish a link, change the value of the updata message sent by the client to 3, and observe the server behavior. Expected result: The server returns the illegal parameter. 2. Establish a link, change the value of the updata message sent by the server to 3, and observe the client behavior.*/ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE); ALERT_Info alertInfo = {0}; ALERT_GetInfo(serverTlsCtx, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_INVALID_REQ_VAL_FUNC_TC002 * @brief 4.6.3. Key and Initialization Vector Update row 178 * 1. Establish a connection, change the value of the updata message sent by the client to 3, and observe the server * behavior. Expected result: The server returns the illegal parameter. * 2. Establish a connection, change the value of the updata message sent by the server to 3, and observe the client * behavior. Expected result: The client returns the illegal parameter. * @expect * 1.Initialization succeeded. * 2.Return ALERT_ILLEGAL_PARAMETER. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_INVALID_REQ_VAL_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); uint8_t data[] = {KEY_UPDATE, 0x00, 0x00, 0x01, 0x03}; ASSERT_TRUE(REC_Write(serverTlsCtx, REC_TYPE_HANDSHAKE, data, sizeof(data)) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); /* 1. Establish a link, change the value of the updata message sent by the client to 3, and observe the server behavior. Expected result: The server returns the illegal parameter. 2. Establish a link, change the value of the updata message sent by the server to 3, and observe the client behavior.*/ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE); ALERT_Info alertInfo = {0}; ALERT_GetInfo(clientTlsCtx, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_NO_REPLY_FUNC_TC001 * @brief 4.6.3. Key and Initialization Vector Update row 179 * 1. After the client receives the update_requested message, the update message returned by the client is lost. * The client continues to send app messages and observe the server behavior. Expected result: The server sends an * alert message and the connection is disconnected. * Analysis: The server application traffic secret is updated on both communication ends, * The client application traffic secret is updated on the client, but the server does not * update the client application traffic secret. When the server sends a message to the client, * the client can parse the message, but the server cannot parse the message. * @expect * 1.the server cannot parse the message and return ALERT_BAD_RECORD_MAC * */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_NO_REPLY_FUNC_TC001() { FRAME_Init(); int32_t ret; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(HITLS_KeyUpdate(server->ssl, HITLS_UPDATE_REQUESTED) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint8_t dest[READ_BUF_SIZE] = {0}; uint32_t readbytes = 0; ASSERT_EQ(HITLS_Read(client->ssl, dest, READ_BUF_SIZE, &readbytes), HITLS_REC_NORMAL_RECV_BUF_EMPTY); /* 1. After the client receives the update_requested message, the update message returned by the client is lost. * The client continues to send app messages and observe the server behavior. */ uint8_t lostBuffer[MAX_RECORD_LENTH] = {0}; uint32_t lostLen = 0; ret = FRAME_TransportSendMsg(client->io, lostBuffer, MAX_RECORD_LENTH, &lostLen); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_NE(lostLen, 0); uint8_t src[] = "Client is sending msg with new application traffic key"; uint32_t writeLen; ASSERT_EQ(HITLS_Write(client->ssl, src, sizeof(src), &writeLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); memset_s(dest, READ_BUF_SIZE, 0, READ_BUF_SIZE); readbytes = 0; ASSERT_EQ(HITLS_Read(server->ssl, dest, READ_BUF_SIZE, &readbytes), HITLS_REC_BAD_RECORD_MAC); ALERT_Info alertInfo = {0}; ALERT_GetInfo(server->ssl, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_BAD_RECORD_MAC); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_NO_REPLY_FUNC_TC002 * @brief 4.6.3. Key and Initialization Vector Update row 179 * 2. When the server receives the update_requested message, the update message returned by the server is lost. * The server continues to send app messages and observe the customer behavior. Expected result: The client sends an * alert message and the connection is disconnected. Analysis: The client application traffic secret is updated at both * communication ends, The server application traffic secret is updated on the server, but the server application * traffic secret is not updated on the client. When the client sends a message to the server, the server can parse the * message, but the server cannot parse the message. * * @expect * 1.the server cannot parse the message and return ALERT_BAD_RECORD_MAC */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_WITH_NO_REPLY_FUNC_TC002() { FRAME_Init(); int32_t ret; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(HITLS_KeyUpdate(client->ssl, HITLS_UPDATE_REQUESTED) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t dest[READ_BUF_SIZE] = {0}; uint32_t readbytes = 0; ASSERT_EQ(HITLS_Read(server->ssl, dest, READ_BUF_SIZE, &readbytes), HITLS_REC_NORMAL_RECV_BUF_EMPTY); /* 2. When the server receives the update_requested message, the update message returned by the server is lost. The * server continues to send app messages and observe the customer behavior. */ uint8_t lostBuffer[MAX_RECORD_LENTH] = {0}; uint32_t lostLen = 0; ret = FRAME_TransportSendMsg(server->io, lostBuffer, MAX_RECORD_LENTH, &lostLen); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_NE(lostLen, 0); uint8_t src[] = "Server is sending msg with new application traffic key"; uint32_t writeLen; ASSERT_EQ(HITLS_Write(server->ssl, src, sizeof(src), &writeLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); memset_s(dest, READ_BUF_SIZE, 0, READ_BUF_SIZE); readbytes = 0; ASSERT_EQ(HITLS_Read(client->ssl, dest, READ_BUF_SIZE, &readbytes), HITLS_REC_BAD_RECORD_MAC); ALERT_Info alertInfo = {0}; ALERT_GetInfo(client->ssl, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_BAD_RECORD_MAC); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_READ_WRITE_AFTER_FATAL_ALEART_FUNC_TC001 * @brief 6. Alert Protocol row 206 * Upon receiving an fatal alert, the TLS implementation SHOULD indicate an error to the application and MUST NOT * allow any further data to be sent or received on the connection. * 1. After receiving the fatal alert, the server invokes the read interface. The invoking fails. * 2. After receiving the fatal alert, the server fails to invoke the write interface. * 3. After receiving the fatal alert, the server fails to invoke the read interface. * 4. After receiving the fatal alert, the server invokes the write interface. The invoking fails. * @expect * 1.the server invokes the read interface fails and return HITLS_CM_LINK_FATAL_ALERTED * 4.the server invokes the write interface fails and return HITLS_CM_LINK_FATAL_ALERTED * */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_READ_WRITE_AFTER_FATAL_ALEART_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); uint8_t data[] = {KEY_UPDATE, 0x00, 0x00, 0x01, 0x03}; ASSERT_TRUE(REC_Write(serverTlsCtx, REC_TYPE_HANDSHAKE, data, sizeof(data)) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); /* 1. Establish a link, change the value of the updata message sent by the client to 3, and observe the server behavior. Expected result: The server returns the illegal parameter. 2. Establish a link, change the value of the updata message sent by the server to 3, and observe the client behavior.*/ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE); ALERT_Info alertInfo = {0}; ALERT_GetInfo(clientTlsCtx, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_ILLEGAL_PARAMETER); ASSERT_EQ(clientTlsCtx->state, CM_STATE_ALERTED); /* 1. After receiving the fatal alert, the server invokes the read interface. */ ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_FATAL_ALERTED); uint8_t src[] = "Hello world"; /* 4. After receiving the fatal alert, the server invokes the write interface. */ uint32_t writeLen; ASSERT_EQ(HITLS_Write(clientTlsCtx, src, sizeof(src), &writeLen), HITLS_CM_LINK_FATAL_ALERTED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_READ_WRITE_AFTER_FATAL_ALEART_FUNC_TC002 * @brief 6. Alert Protocol row 206 * Upon receiving an fatal alert, the TLS implementation SHOULD indicate an error to the application and MUST NOT * allow any further data to be sent or received on the connection. * 1. After receiving the fatal alert, the server invokes the read interface. The invoking fails. * 2. After receiving the fatal alert, the server fails to invoke the write interface. * 3. After receiving the fatal alert, the server fails to invoke the read interface. * 4. After receiving the fatal alert, the server invokes the write interface. The invoking fails. * @expect * 1.the server invokes the read interface fails and return HITLS_CM_LINK_FATAL_ALERTED * 4.the server invokes the write interface fails and return HITLS_CM_LINK_FATAL_ALERTED * */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_READ_WRITE_AFTER_FATAL_ALEART_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); uint8_t data[] = {KEY_UPDATE, 0x00, 0x00, 0x01, 0x03}; ASSERT_TRUE(REC_Write(clientTlsCtx, REC_TYPE_HANDSHAKE, data, sizeof(data)) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_MSG_HANDLE_ILLEGAL_KEY_UPDATE_TYPE); ALERT_Info alertInfo = {0}; ALERT_GetInfo(serverTlsCtx, &alertInfo); ASSERT_EQ(alertInfo.description, ALERT_ILLEGAL_PARAMETER); ASSERT_EQ(serverTlsCtx->state, CM_STATE_ALERTED); /* 1. After receiving the fatal alert, the server invokes the read interface. */ ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_FATAL_ALERTED); uint8_t src[] = "Hello world"; /* 4. After receiving the fatal alert, the server invokes the write interface. */ uint32_t writeLen; ASSERT_EQ(HITLS_Write(serverTlsCtx, src, sizeof(src), &writeLen), HITLS_CM_LINK_FATAL_ALERTED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC001 * @brief 4.6.3. Key and Initialization Vector Update row 175 * The KeyUpdate message can be sent by any peer after the Finished message is sent. * An implementation that receives a KeyUpdate message before receiving a Finished message must terminate the * connection with an unexpected_message alert. When the client receives the Finish message, construct abnormal * packets so that the client receives the Updata message and observe the next message sent by the client. * Expected result: The next ALERT_UNEXPECTED_MESSAGE message is sent. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); bool isRecRead = true; RecWrapper wrapper = {TRY_RECV_FINISH, REC_TYPE_HANDSHAKE, isRecRead, NULL, Test_ModifyFinish}; RegisterWrapper(wrapper); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC002 * @brief 4.6.3. Key and Initialization Vector Update row 175 * The KeyUpdate message can be sent by any peer after the Finished message is sent. * An implementation that receives a KeyUpdate message before receiving a Finished message must terminate the * connection with an unexpected_message alert. When the server receives the Finish message, construct abnormal packets * so that the server receives the Updata message and observe the next message sent by the server. Expected result: The * next ALERT_UNEXPECTED_MESSAGE message is sent. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); bool isRecRead = true; ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH) == HITLS_SUCCESS); RecWrapper wrapper = {TRY_RECV_FINISH, REC_TYPE_HANDSHAKE, isRecRead, NULL, Test_ModifyFinish}; RegisterWrapper(wrapper); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC003 * @brief 4.6.3. Key and Initialization Vector Update row 175 * The KeyUpdate message can be sent by any peer after the Finished message is sent. * An implementation that receives a KeyUpdate message before receiving a Finished message must terminate the * connection with an unexpected_message alert. When the client receives the Finish message, construct an abnormal * packet so that the client receives the Update message and observe the next message sent by the client. Expected * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); bool isRecRead = true; RecWrapper wrapper = {TRY_RECV_FINISH, REC_TYPE_HANDSHAKE, isRecRead, NULL, Test_ModifyFinish}; RegisterWrapper(wrapper); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(tlsConfig, &cipherSuite, 1); HITLS_CFG_SetPskClientCallback(tlsConfig, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(tlsConfig, (HITLS_PskServerCb)ExampleServerCb); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC004 * @brief 4.6.3. Key and Initialization Vector Update row 175 * The KeyUpdate message can be sent by any peer after the Finished message is sent. * An implementation that receives a KeyUpdate message before receiving a Finished message must terminate the * connection with an unexpected_message alert. When the PSK session is resumed and the connection is established, the * client constructs an abnormal packet so that the client receives the update message and observes the next message * sent by the client. Expected result: The next ALERT_UNEXPECTED_MESSAGE message is sent. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC004() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); HITLS_SetSession(client->ssl, clientSession); bool isRecRead = true; RecWrapper wrapper = {TRY_RECV_FINISH, REC_TYPE_HANDSHAKE, isRecRead, NULL, Test_ModifyFinish}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC005 * @brief 4.6.3. Key and Initialization Vector Update row 175 * The KeyUpdate message can be sent by any peer after the Finished message is sent. * When the server receives the finish message, construct an abnormal packet so that the server receives the update * message and observe the next message sent by the server. Expected result: The next ALERT_UNEXPECTED_MESSAGE message * is sent. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC005() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(tlsConfig, &cipherSuite, 1); HITLS_CFG_SetPskClientCallback(tlsConfig, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(tlsConfig, (HITLS_PskServerCb)ExampleServerCb); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH) == HITLS_SUCCESS); bool isRecRead = true; RecWrapper wrapper = {TRY_RECV_FINISH, REC_TYPE_HANDSHAKE, isRecRead, NULL, Test_ModifyFinish}; RegisterWrapper(wrapper); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC006 * @brief 4.6.3. Key and Initialization Vector Update row 175 * The KeyUpdate message can be sent by any peer after the Finished message is sent. * When the PSK session is resumed and the connection is established, the server constructs an abnormal packet so that * the server receives the update message and observes the next message sent by the server. Expected result: The next * ALERT_UNEXPECTED_MESSAGE message is sent. * @expect * 1.Initialization succeeded. * 2.Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYUPDATE_BEFORE_FINISH_FUNC_TC006() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); HITLS_SetSession(client->ssl, clientSession); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH) == HITLS_SUCCESS); bool isRecRead = true; RecWrapper wrapper = {TRY_RECV_FINISH, REC_TYPE_HANDSHAKE, isRecRead, NULL, Test_ModifyFinish}; RegisterWrapper(wrapper); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECVAPP_AFTER_CERT_FUNC_TC001 * @spec A Finished message MUST be sent regardless of whether the Certificate message is empty. * @brief 4.4.2. Certificate row114 * 1. The certificate message sent by the server is not empty and the app message is directly sent. * Expected result: The handshake between the two parties fails. The client sends an unexpected message alert. The level * is ALERT_Level_FATAL, the description is ALERT_UNEXPECTED_MESSAGE, and the handshake is interrupted. * 2. Dual-end verification: The peer certificate can be empty, the certificate message sent by the client is empty, and * the app message is directly sent. Expected result: The handshake between the two parties fails. The server sends an * unexpected message alert. The level is ALERT_Level_FATAL, the description is ALERT_UNEXPECTED_MESSAGE, and the * handshake is interrupted. * @expect * 1.Handshake failed. The client sends ALERT_UNEXPECTED_MESSAGE. * 2.Handshake failed. The server sends ALERT_UNEXPECTED_MESSAGE. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECVAPP_AFTER_CERT_FUNC_TC001(int isClient) { FRAME_Init(); STUB_Init(); FRAME_CertInfo certInfo = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", 0, 0, 0, 0, }; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); /* 1. The certificate message sent by the server is not empty and the app message is directly sent. * tlsConfig->isSupportClientVerify = true; * 2. Dual-end verification: The peer certificate can be empty, the certificate message sent by the client is empty, * and the app message is directly sent. */ tlsConfig->isSupportNoClientCert = true; uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(tlsConfig, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); FRAME_LinkObj *client = FRAME_CreateLinkWithCert(tlsConfig, BSL_UIO_TCP, &certInfo); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); if (isClient) { ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); } else { ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH) == HITLS_SUCCESS); } FuncStubInfo stubInfo = {0}; /* * Plaintext header of the wrapped record, which is of the app type for finish and app data. * After the wrapped record body is parsed (that is, the body is decrypted), the last nonzero byte of the body is * the actual record type. This case is constructed by tampering with the rec type to the app type, which should be * the hs type. */ STUB_Replace(&stubInfo, RecParseInnerPlaintext, STUB_RecParseInnerPlaintext); if (isClient) { ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); } else { ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&stubInfo); } /* END_CASE */ static int32_t SendCcs(HITLS_Ctx *ctx, uint8_t *data, uint8_t len) { return REC_Write(ctx, REC_TYPE_CHANGE_CIPHER_SPEC, data, len); } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC001 * @spec * 1. If the server receives a CCS message before receiving the client hello message, the server sends the * unexpected_message alarm to terminate the connection. * @brief If an implementation detects a change_cipher_spec record received before the first ClientHello * message or after the peer' s Finished message, it MUST be treated as an unexpected record type. * 5. Record Protocol row 183 * @expect * 1.the server sends the ALERT_UNEXPECTED_MESSAGE and terminate the connection. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_CLIENT_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(client->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioServerData->sndMsg.msg, ioServerData->sndMsg.len) == EOK); sndMsg.len = ioServerData->sndMsg.len; ioServerData->sndMsg.len = 0; uint8_t data = 1; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC002 * @spec * 1. After receiving the finished message and CCS message, the client sends the unexpected_message alarm to terminate * the connection. * 2. After receiving the finished message and CCS message, the server sends the unexpected_message alarm to terminate * the connection. * @brief If an implementation detects a change_cipher_spec record received before the first ClientHello * message or after the peer' s Finished message, it MUST be treated as an unexpected record type. * 5. Record Protocol row 183 * @expect * 1.the client sends the ALERT_UNEXPECTED_MESSAGE and terminate the connection. * 2.the server sends the ALERT_UNEXPECTED_MESSAGE and terminate the connection. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC002(int isClient) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint8_t data = 1; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; if (isClient != 0) { ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 2. After receiving the finished message and CCS message, the server sends the unexpected_message alarm to * terminate the connection. */ ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); } else { memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE); ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 1. After receiving the finished message and CCS message, the client sends the unexpected_message alarm to * terminate the connection. */ ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ZERO_APPMSG_FUNC_TC001 * @spec * 1. Establish a connection. After the connection is established, construct an APPdata message with 0 length and send * it to the server. Then, send an APPdata message with data to the server. The message can be received normally. * 2. Establish a connection. After the connection is established, construct an APPdata message with zero length and * send it to the client. Then, send an APPdata message with data to the client. The message can be received normally. * @brief Zero-length fragments of Application Data MAY be sent, as they are potentially useful as a traffic analysis * countermeasure. 5.1. Record Layer row 189 * @expect * 1.The connection is successfully established and received normally. * 2.The connection is successfully established and received normally. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ZERO_APPMSG_FUNC_TC001(int isZeroClient) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); uint8_t data[] = ""; uint8_t appData[] = "hello world"; uint8_t serverData[READ_BUF_SIZE] = {0}; uint8_t clientData[READ_BUF_SIZE] = {0}; ASSERT_TRUE((sizeof(data) <= READ_BUF_SIZE) && (sizeof(appData) <= READ_BUF_SIZE)); if (isZeroClient != 0) { /* 1. Establish a connection. After the connection is established, construct an APPdata message with 0 length * and send it to the server. Then, send an APPdata message with data to the server. */ (void)memcpy_s(clientData, READ_BUF_SIZE, data, sizeof(data)); (void)memcpy_s(serverData, READ_BUF_SIZE, appData, sizeof(appData)); } else { /* 2. Establish a connection. After the connection is established, construct an APPdata message with zero length * and send it to the client. Then, send an APPdata message with data to the client. */ (void)memcpy_s(clientData, READ_BUF_SIZE, appData, sizeof(appData)); (void)memcpy_s(serverData, READ_BUF_SIZE, data, sizeof(data)); } size_t serverDataSize = strlen((char *)serverData) + 1; size_t clientDataSize = strlen((char *)clientData) + 1; uint32_t writeLen; ASSERT_EQ(HITLS_Write(server->ssl, serverData, serverDataSize, &writeLen), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_TRUE(readLen == serverDataSize && memcmp(serverData, readBuf, readLen) == 0); ASSERT_EQ(HITLS_Write(client->ssl, clientData, clientDataSize, &writeLen), HITLS_SUCCESS); memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE); readLen = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_TRUE(readLen == clientDataSize && memcmp(clientData, readBuf, readLen) == 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_INCORRECT_LENGTH_CHMSG_FUNC_TC001 * @spec * 1. If the server receives a ClientHello whose length exceeds the length of the entire packet, the server sends a * decode_error alarm and the handshake fails. * @brief Peers which receive a message which cannot be parsed according to the syntax (e.g., * have a length extending beyond the message boundary or contain an out-of-range length) * MUST terminate the connection with a "decode_error" alert. * 6. Alert Protocol row 209 * @expect * 1.The server sends a ALERT_DECODE_ERROR and the handshake fails. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_INCORRECT_LENGTH_CHMSG_FUNC_TC001(void) { FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportClientVerify = true; FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->extensionLen.state = ASSIGNED_FIELD; clientMsg->extensionLen.data = clientMsg->extensionLen.data + 1; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(server->ssl != NULL); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info alert = {0}; ALERT_GetInfo(server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_DECODE_ERROR); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLOSE_NOTIFY_FUNC_TC001 * @spec * Establish a connection between the client and server, and then close the connection on the client. Check whether * the message sent by the client is a close_notify message. * @brief The "close_notify" alert is used to indicate orderly closure of one direction of the connection. Upon * receiving such an alert, the TLS implementation SHOULD indicate end-of-data to the application. * 6.0.0. Alert Protocol row 205 * @expect * 1.The client sends a ALERT_CLOSE_NOTIFY message. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLOSE_NOTIFY_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(client->io); FRAME_Msg clientframeMsg = {0}; uint8_t *clientbuffer = clientioUserData->sndMsg.msg; uint32_t clientreadLen = clientioUserData->sndMsg.len; uint32_t clientparseLen = 0; int32_t ret = ParserTotalRecord(client, &clientframeMsg, clientbuffer, clientreadLen, &clientparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(clientframeMsg.type == REC_TYPE_ALERT && clientframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(clientframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && clientframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); FrameUioUserData *serverioUserData = BSL_UIO_GetUserData(server->io); FRAME_Msg serverframeMsg = {0}; uint8_t *serverbuffer = serverioUserData->recMsg.msg; uint32_t serverreadLen = serverioUserData->recMsg.len; uint32_t serverparseLen = 0; ret = ParserTotalRecord(server, &serverframeMsg, serverbuffer, serverreadLen, &serverparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(serverframeMsg.type == REC_TYPE_ALERT && serverframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(serverframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && serverframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLOSE_NOTIFY_FUNC_TC003 * @spec * Establish a connection between the client and server, and then close the connection on the server. Obtain the * message sent by the server and check whether the message is close_notify. * @brief The "close_notify" alert is used to indicate orderly closure of one direction of the connection. Upon * receiving such an alert, the TLS implementation SHOULD indicate end-of-data to the application. * 6.0.0. Alert Protocol row 205 * @expect * 1.The server sends a ALERT_CLOSE_NOTIFY message. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLOSE_NOTIFY_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(server, client, false, TRY_SEND_CERTIFICATE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(HITLS_Close(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_CLOSED); FrameUioUserData *serverioUserData = BSL_UIO_GetUserData(server->io); FRAME_Msg serverframeMsg = {0}; uint8_t *serverbuffer = serverioUserData->sndMsg.msg; uint32_t serverreadLen = serverioUserData->sndMsg.len; uint32_t serverparseLen = 0; int32_t ret = ParserTotalRecord(server, &serverframeMsg, serverbuffer, serverreadLen, &serverparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(serverframeMsg.type == REC_TYPE_ALERT && serverframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(serverframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && serverframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(client->io); FRAME_Msg clientframeMsg = {0}; uint8_t *clientbuffer = clientioUserData->recMsg.msg; uint32_t clientreadLen = clientioUserData->recMsg.len; uint32_t clientparseLen = 0; ret = ParserTotalRecord(client, &clientframeMsg, clientbuffer, clientreadLen, &clientparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(clientframeMsg.type == REC_TYPE_ALERT && clientframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(clientframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && clientframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_WRITE_FUNC_TC001 * @spec * After the client sends the close_notify message, the client fails to invoke the write interface. * @brief Either party MAY initiate a close of its write side of the connection by sending a "close_notify" alert. Any * data received after a closure alert has been received MUST be ignored. * 6.1.0. Alert Protocol row 213 * @expect * 1.The client fails to invoke the write interface and send HITLS_CM_LINK_CLOSED */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_WRITE_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(client->io); FRAME_Msg clientframeMsg = {0}; uint8_t *clientbuffer = clientioUserData->sndMsg.msg; uint32_t clientreadLen = clientioUserData->sndMsg.len; uint32_t clientparseLen = 0; int32_t ret = ParserTotalRecord(client, &clientframeMsg, clientbuffer, clientreadLen, &clientparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(clientframeMsg.type == REC_TYPE_ALERT && clientframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(clientframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && clientframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_EQ(HITLS_Write(client->ssl, data, sizeof(data), &writeLen), HITLS_CM_LINK_CLOSED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CLOSE_NOTIFY_WRITE_FUNC_TC001 * @spec * After the server sends the close_notify message, the write interface fails to be invoked. * @brief Either party MAY initiate a close of its write side of the connection by sending a "close_notify" alert. Any * data received after a closure alert has been received MUST be ignored. * 6.1.0. Alert Protocol row 213 * @expect * 1.The server fails to invoke the write interface and send HITLS_CM_LINK_CLOSED */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CLOSE_NOTIFY_WRITE_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(server, client, false, TRY_SEND_CERTIFICATE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(HITLS_Close(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_CLOSED); FrameUioUserData *serverioUserData = BSL_UIO_GetUserData(server->io); FRAME_Msg serverframeMsg = {0}; uint8_t *serverbuffer = serverioUserData->sndMsg.msg; uint32_t serverreadLen = serverioUserData->sndMsg.len; uint32_t serverparseLen = 0; int32_t ret = ParserTotalRecord(server, &serverframeMsg, serverbuffer, serverreadLen, &serverparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(serverframeMsg.type == REC_TYPE_ALERT && serverframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(serverframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && serverframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_EQ(HITLS_Write(server->ssl, data, sizeof(data), &writeLen), HITLS_CM_LINK_CLOSED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_RECV_CLOSE_NOTIFY_CLIENTHELLO_FUNC_TC001 * @spec * The connection is established normally. After receiving the close_notify message, the server receives the clienthello * message. The message is ignored and the connection is interrupted. * @brief close_notify: This alert notifies the recipient that the sender will not send any more messages on this * connection. Any data received after a closure alert has been received MUST be ignored. * 6.1.0. Alert Protocol row 211 * @expect * 1.The connection is interrupted and return HITLS_CM_LINK_FATAL_ALERTED */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_RECV_CLOSE_NOTIFY_CLIENTHELLO_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); FrameUioUserData *clientioUserData = BSL_UIO_GetUserData(client->io); FRAME_Msg clientframeMsg = {0}; uint8_t *clientbuffer = clientioUserData->sndMsg.msg; uint32_t clientreadLen = clientioUserData->sndMsg.len; uint32_t clientparseLen = 0; int32_t ret = ParserTotalRecord(client, &clientframeMsg, clientbuffer, clientreadLen, &clientparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(clientframeMsg.type == REC_TYPE_ALERT && clientframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(clientframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && clientframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); FrameUioUserData *serverioUserData = BSL_UIO_GetUserData(server->io); FRAME_Msg serverframeMsg = {0}; uint8_t *serverbuffer = serverioUserData->recMsg.msg; uint32_t serverreadLen = serverioUserData->recMsg.len; uint32_t serverparseLen = 0; ret = ParserTotalRecord(server, &serverframeMsg, serverbuffer, serverreadLen, &serverparseLen); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(serverframeMsg.type == REC_TYPE_ALERT && serverframeMsg.bodyLen == ALERT_BODY_LEN); ASSERT_TRUE(serverframeMsg.body.alertMsg.level == ALERT_LEVEL_WARNING && serverframeMsg.body.alertMsg.description == ALERT_CLOSE_NOTIFY); ASSERT_TRUE(server->ssl != NULL); serverioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_IO_BUSY); serverioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_CM_LINK_FATAL_ALERTED); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); serverioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(server->ssl != NULL); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_CM_LINK_FATAL_ALERTED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_HRR_FUNC_TC001 * @spec * The connection is established normally. After the client receives the close_notify message and the * helloRetryRequest message, the client ignores the message and disconnects from the connection. * @brief close_notify: This alert notifies the recipient that the sender will not send any more messages on this * connection. Any data received after a closure alert has been received MUST be ignored. * 6.1.0. Alert Protocol row 211 * @expect * 1.The connection is interrupted and return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_HRR_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; HITLS_CFG_SetGroups(config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_LEVEL_WARNING, &frameMsg.body.alertMsg.alertLevel) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_CLOSE_NOTIFY, &frameMsg.body.alertMsg.alertDescription) == HITLS_SUCCESS); uint8_t alertBuf[MAX_RECORD_LENTH] = {0}; uint32_t alertLen = MAX_RECORD_LENTH; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, alertBuf, alertLen, &alertLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, alertBuf, alertLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_CM_LINK_CLOSED); ASSERT_NE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_APP_FUNC_TC001 * @spec * The connection is established normally. After the client receives the close_notify message and the app message, the * client ignores the message and disconnects the connection. * @brief close_notify: This alert notifies the recipient that the sender will not send any more messages on this * connection. Any data received after a closure alert has been received MUST be ignored. * 6.1.0. Alert Protocol row 211 * @expect * 1.The connection is interrupted and return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_APP_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_LEVEL_WARNING, &frameMsg.body.alertMsg.alertLevel) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_CLOSE_NOTIFY, &frameMsg.body.alertMsg.alertDescription) == HITLS_SUCCESS); uint8_t alertBuf[MAX_RECORD_LENTH] = {0}; uint32_t alertLen = MAX_RECORD_LENTH; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, alertBuf, alertLen, &alertLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, alertBuf, alertLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_NE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC001 * @spec * When the connection is established, the server sends some error alarms and closes the write end of the connection. * The close_notify message is not sent. * @brief Each party MUST send a "close_notify" alert before closing its write side of the connection, unless it has * already sent some error alert. This does not have any effect on its read side of the connection. * 6.1.0. Alert Protocol row 214 * @expect * 1.The close_notify message is not sent. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); /* The client invokes the HITLS_Connect, and the handshake process is not complete.Check the status of the security connection.The status is CM_STATE_CALL. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_LEVEL_FATAL, &frameMsg.body.alertMsg.alertLevel) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_DECODE_ERROR, &frameMsg.body.alertMsg.alertDescription) == HITLS_SUCCESS); uint8_t alertBuf[MAX_RECORD_LENTH] = {0}; uint32_t alertLen = MAX_RECORD_LENTH; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, alertBuf, alertLen, &alertLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, alertBuf, alertLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); ALERT_Info alert = {0}; ALERT_GetInfo(client->ssl, &alert); ASSERT_NE(alert.level, ALERT_LEVEL_WARNING); ASSERT_NE(alert.description, ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC002 * @spec * If the connection is established normally, the client sends some error alarms and closes the write end of the * connection. The close_notify message is not sent. * @brief Each party MUST send a "close_notify" alert before closing its write side of the connection, unless it has * already sent some error alert. This does not have any effect on its read side of the connection. * 6.1.0. Alert Protocol row 214 * @expect * 1.The close_notify message is not sent. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_LEVEL_FATAL, &frameMsg.body.alertMsg.alertLevel) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_ModifyMsgInteger(ALERT_DECODE_ERROR, &frameMsg.body.alertMsg.alertDescription) == HITLS_SUCCESS); uint8_t alertBuf[MAX_RECORD_LENTH] = {0}; uint32_t alertLen = MAX_RECORD_LENTH; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, alertBuf, alertLen, &alertLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, alertBuf, alertLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(server->ssl != NULL); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(HITLS_Close(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_CLOSED); ALERT_Info alert = {0}; ALERT_GetInfo(server->ssl, &alert); ASSERT_NE(alert.level, ALERT_LEVEL_WARNING); ASSERT_NE(alert.description, ALERT_CLOSE_NOTIFY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC003 * @spec * A connection is set up and the client is disconnected. Before the client receives a response, the client fails to * invoke the read interface. After receiving the close_notify message, the server suspends the write end and returns a * close_notify message to close the read end. * @brief Each party MUST send a "close_notify" alert before closing its write side of the connection, unless it has * already sent some error alert. This does not have any effect on its read side of the connection. * 6.1.0. Alert Protocol row 214 * @expect * @expect The server receives the close_notify message and responds to the close_notify message. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_CLOSED); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_CM_LINK_CLOSED); ASSERT_EQ(server->ssl->shutdownState, HITLS_RECEIVED_SHUTDOWN); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC004 * @spec * A connection is set up and the server is disconnected. Before receiving a response, the server fails to invoke the * read interface. After receiving the close_notify message, the client suspends the write end and responds with the * close_notify message to close the read end. * @brief Each party MUST send a "close_notify" alert before closing its write side of the connection, unless it has * already sent some error alert. This does not have any effect on its read side of the connection. * 6.1.0. Alert Protocol row 214 * @expect The client receives the close_notify message and responds to the close_notify message. */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CLOSE_NOTIFY_READ_FUNC_TC004(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Close(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_CLOSED); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_CLOSED); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_CM_LINK_CLOSED); ASSERT_EQ(client->ssl->shutdownState, HITLS_RECEIVED_SHUTDOWN); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ int32_t DefaultCfgStatusParkWithSuite_1_3(HandshakeTestInfo *testInfo) { FRAME_Init(); testInfo->config = HITLS_CFG_NewTLS13Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(testInfo->config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; return StatusPark(testInfo); } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC001 * @spec - * @title During connection establishment, the server receives a message of the undefined record type after sending the finished message. In this case, an alert message is returned. * @precon nan * @brief 1. Use the default configuration on the client and server, and disable the peer end verification function on * the server. Expected result 1 is obtained. * 2. When the client initiates a TLS connection request in the RECV_Client_Hello message, construct an APP message * and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.version = HITLS_VERSION_TLS13; /* 1. Use the default configuration on the client and server, and disable the peer end verification function on * the server. */ testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(testInfo.server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_RECV_FINISH), HITLS_SUCCESS); /* 2. When the client initiates a TLS connection request in the RECV_Client_Hello message, construct an APP message * and send it to the client. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; uint8_t appdata[] = {0xff, 0x03, 0x03, 0x00, 0x02, 0x01, 0x01}; ASSERT_EQ(memcpy_s(data, len, appdata, sizeof(appdata)), EOK); ASSERT_EQ( memcpy_s(data + sizeof(appdata), len - sizeof(appdata), ioUserData->recMsg.msg, ioUserData->recMsg.len), EOK); ASSERT_EQ(memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, ioUserData->recMsg.len + sizeof(appdata)), EOK); ioUserData->recMsg.len += sizeof(appdata); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(testInfo.server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC002 * @spec - * @title After the connection is established, renegotiation is not enabled. The server receives the client hello message and * is expected to return an alert message. * @precon nan * @brief 1. Use the default configuration on the client and server, and disable the peer end check function on the * server. Expected result 1 is obtained. * 2. After the connection is set up, do not enable renegotiation and the server receives the client hello message. * Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.version = HITLS_VERSION_TLS13; /* 1. Use the default configuration on the client and server, and disable the peer end check function on the * server. */ testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_RECV_CLIENT_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioUserData->recMsg.msg + REC_TLS_RECORD_HEADER_LEN, ioUserData->recMsg.len - REC_TLS_RECORD_HEADER_LEN) == EOK); sndMsg.len = ioUserData->recMsg.len - REC_TLS_RECORD_HEADER_LEN; ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); REC_Write(testInfo.client->ssl, REC_TYPE_HANDSHAKE, sndMsg.msg, sndMsg.len); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.client, testInfo.server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; /* 2. After the link is set up, do not enable renegotiation and the server receives the client hello message. */ ASSERT_EQ(HITLS_Read(testInfo.server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC003 * @spec - * @title After initialization is complete, construct an app message and send it to the server. The expected alert is * returned. * @precon nan * @brief 1. Use the default configuration on the client and server, and disable the peer end verification function on * the server. Expected result 1 is obtained. * 2. When the client initiates a TLS connection application request, construct an APP message and send it to the * server in the RECV_CLIENT_HELLO message on the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The server sends the ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC003(void) { FRAME_Msg parsedAlert = {0}; HandshakeTestInfo testInfo = {0}; testInfo.isClient = false; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportClientVerify = false; /* 1. Use the default configuration on the client and server, and disable the peer end verification function on * the server. */ ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == 0); /* 2. When the client initiates a TLS connection application request, construct an APP message and send it to the * server in the RECV_CLIENT_HELLO message on the server. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; uint8_t appdata[] = {0x17, 0x03, 0x03, 0x00, 0x02, 0x01, 0x01}; ASSERT_EQ(memcpy_s(data, len, appdata, sizeof(appdata)), EOK); ASSERT_EQ( memcpy_s(data + sizeof(appdata), len - sizeof(appdata), ioUserData->recMsg.msg, ioUserData->recMsg.len), EOK); ASSERT_EQ(memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, ioUserData->recMsg.len + sizeof(appdata)), EOK); ioUserData->recMsg.len += sizeof(appdata); ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); uint32_t parseLen = 0; ASSERT_TRUE(FRAME_ParseTLSNonHsRecord(sndBuf, sndLen, &parsedAlert, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(parsedAlert.recType.data, REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedAlert.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC004 * @spec - * @title After initialization, construct an app message and send it to the client. The expected alert is returned. * @precon nan * @brief 1. Use the default configuration on the client and server, and disable peer verification on the server. * Expected result 1 is obtained. * 2. When the client initiates a TLS connection application request in the RECV_SERVER_HELLO message, construct an * APP message and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC004(void) { FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; HandshakeTestInfo testInfo = {0}; testInfo.isClient = true; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportClientVerify = false; /* 1. Use the default configuration on the client and server, and disable peer verification on the server. */ ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == 0); /* 2. When the client initiates a TLS connection application request in the RECV_SERVER_HELLO message, construct an * APP message and send it to the client. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; uint8_t appdata[] = {0x17, 0x03, 0x03, 0x00, 0x02, 0x01, 0x01}; ASSERT_EQ(memcpy_s(data, len, appdata, sizeof(appdata)), EOK); ASSERT_EQ( memcpy_s(data + sizeof(appdata), len - sizeof(appdata), ioUserData->recMsg.msg, ioUserData->recMsg.len), EOK); ASSERT_EQ(memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, ioUserData->recMsg.len + sizeof(appdata)), EOK); ioUserData->recMsg.len += sizeof(appdata); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); uint32_t parseLen = 0; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.recType.data, REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_TRUE(alertMsg->alertDescription.data == ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC005 * @spec - * @title After the connection is established, the client receives the serverhello message when receiving the app data. The * client is expected to return an alert message. * @precon nan * @brief 1. Use the default configuration on the client and server, and disable peer verification on the server. * Expected result 1 is obtained. * 2. The client initiates a TLS connection request. After the handshake succeeds, the server constructs a * serverhello message and sends it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC005() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.version = HITLS_VERSION_TLS13; /* 1. Use the default configuration on the client and server, and disable peer verification on the server. */ testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); /* 2. The client initiates a TLS connection request. After the handshake succeeds, the server constructs a * serverhello message and sends it to the client. */ ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioUserData->recMsg.msg + REC_TLS_RECORD_HEADER_LEN, ioUserData->recMsg.len - REC_TLS_RECORD_HEADER_LEN) == EOK); sndMsg.len = ioUserData->recMsg.len - REC_TLS_RECORD_HEADER_LEN; ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); REC_Write(testInfo.server->ssl, REC_TYPE_HANDSHAKE, sndMsg.msg, sndMsg.len); // Inject packets to the client. ASSERT_EQ(FRAME_TrasferMsgBetweenLink(testInfo.server, testInfo.client), HITLS_SUCCESS); /* The server invokes HITLS_Read to receive data. */ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC006 * @spec - * @title After the connection is established, the client receives an unknown message when receiving app data and is * expected to return an alert message. * @precon nan * @brief 1. Use the default configuration on the client and server, and disable peer verification on the server. * Expected result 1 is displayed. * 2. The client initiates a TLS connection request. After the handshake succeeds, the client constructs an unknown * message and sends it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECT_RECODETYPE_FUNC_TC006() { FRAME_Init(); ResumeTestInfo testInfo = {0}; /* 1. Use the default configuration on the client and server, and disable peer verification on the server. */ testInfo.uioType = BSL_UIO_TCP; testInfo.version = HITLS_VERSION_TLS13; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(testInfo.client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); /* 2. The client initiates a TLS connection request. After the handshake succeeds, the client constructs an unknown * message and sends it to the client. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; uint8_t appdata[] = {0xff, 0x03, 0x03, 0x00, 0x02, 0x01, 0x01}; ASSERT_EQ(memcpy_s(data, len, appdata, sizeof(appdata)), EOK); ASSERT_EQ( memcpy_s(data + sizeof(appdata), len - sizeof(appdata), ioUserData->recMsg.msg, ioUserData->recMsg.len), EOK); ASSERT_EQ(memcpy_s(ioUserData->recMsg.msg, MAX_RECORD_LENTH, data, ioUserData->recMsg.len + sizeof(appdata)), EOK); ioUserData->recMsg.len += sizeof(appdata); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(testInfo.client->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ #define BUF_TOOLONG_LEN ((1 << 14) + 1) /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC003 * @spec - * @title The client sends a Change Cipher Spec message with the length of 2 ^ 14 + 1 byte. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the client initiates a DTLS connection establishment request and sends a Change Cipher Spec message, the * client modifies one field as follows: Length is 2 ^ 14 + 1. After the modification is complete, send the * modification to the server. Expected result 2 is obtained. * 3. When the server receives the Change Cipher Spec message, check the value returned by the HITLS_Accept * interface. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The field is successfully modified and sent to the client. * 3. The return value of the HITLS_Accept interface is HITLS_REC_NORMAL_RECV_BUF_EMPTY. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC003(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_FINISH; testInfo.isClient = false; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; /* 1. Use the default configuration items to configure the client and server. */ ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == HITLS_SUCCESS); ASSERT_EQ( FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, TRY_RECV_FINISH), HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); /* 2. When the client initiates a DTLS connection establishment request and sends a Change Cipher Spec message, the * client modifies one field as follows: Length is 2 ^ 14 + 1. After the modification is complete, send the * modification to the server. */ uint8_t *certDataTemp = (uint8_t *)BSL_SAL_Calloc(1, (uint32_t)BUF_TOOLONG_LEN); ASSERT_TRUE(certDataTemp != NULL); BSL_SAL_FREE(frameMsg.body.ccsMsg.extra.data); frameMsg.body.ccsMsg.extra.data = certDataTemp; frameMsg.body.ccsMsg.extra.size = BUF_TOOLONG_LEN; frameMsg.body.ccsMsg.extra.state = ASSIGNED_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(testInfo.server->ssl != NULL); /* 3. When the server receives the Change Cipher Spec message, check the value returned by the HITLS_Accept * interface. */ ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_FINISH); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC004 * @spec - * @title The client sends a Change Cipher Spec message with the length of 2 ^ 14 + 1 byte. * @precon nan * @brief 1. Use the default configuration items to configure the client and client. Expected result 1 is obtained. * 2. When the client initiates a DTLS connection establishment request and sends a Change Cipher Spec message, the client modifies one field as follows: Length is 2 ^ 14 + 1. After the modification is complete, send the modification to the client. Expected result 2 is obtained. 3. When the client receives the Change Cipher Spec message, check the value returned by the HITLS_Accept interface. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The field is successfully modified and sent to the client. 3. The return value of the HITLS_Accept interface is HITLS_REC_NORMAL_RECV_BUF_EMPTY. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC004(void) { HandshakeTestInfo testInfo = {0}; testInfo.state = TRY_RECV_FINISH; testInfo.isClient = true; testInfo.isSupportExtendMasterSecret = true; testInfo.isSupportClientVerify = true; /* 1. Use the default configuration items to configure the client and server. */ ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == HITLS_SUCCESS); ASSERT_EQ( FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, TRY_RECV_FINISH), HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); /* 2. When the client initiates a DTLS connection establishment request and sends a Change Cipher Spec message, the * client modifies one field as follows: Length is 2 ^ 14 + 1. After the modification is complete, send the * modification to the server. */ uint8_t *certDataTemp = (uint8_t *)BSL_SAL_Calloc(1, (uint32_t)BUF_TOOLONG_LEN); ASSERT_TRUE(certDataTemp != NULL); BSL_SAL_FREE(frameMsg.body.ccsMsg.extra.data); frameMsg.body.ccsMsg.extra.data = certDataTemp; frameMsg.body.ccsMsg.extra.size = BUF_TOOLONG_LEN; frameMsg.body.ccsMsg.extra.state = ASSIGNED_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(testInfo.client->ssl != NULL); /* 3. When the client receives the Change Cipher Spec message, check the value returned by the HITLS_Accept * interface. */ ASSERT_EQ(HITLS_Accept(testInfo.client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(testInfo.client->ssl->hsCtx->state == TRY_RECV_FINISH); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC001 * @spec - * @titleThe client sends a clienthello message with the length of 2 ^ 14 + 1 byte. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. When the client initiates a DTLS connection creation request, the client needs to send a client hello message, * modify the following field as follows: Length is 2 ^ 14 + 1. After the modification, the modification is * sent to the server. Expected result 2 is obtained. * 3. When the server receives the client hello message, check the value returned by the HITLS_Accept * interface. Expected result 3 is obtained. * @expect 1. The initialization is successful. * 2. The field is successfully modified and sent to the client. * 3. The return value of the HITLS_Accept interface is HITLS_REC_NORMAL_RECV_BUF_EMPTY. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; /* 1. Use the default configuration items to configure the client and server. */ ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* 2. When the client initiates a DTLS connection creation request, the client needs to send a client hello message, * modify the following field as follows: Length is 2 ^ 14 + 1. After the modification, the modification is * sent to the server. */ FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; uint8_t *certDataTemp = (uint8_t *)BSL_SAL_Calloc(1, (uint32_t)BUF_TOOLONG_LEN); ASSERT_TRUE(certDataTemp != NULL); BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientHello.sessionId.data); clientMsg->sessionId.state = ASSIGNED_FIELD; clientMsg->sessionId.size = BUF_TOOLONG_LEN; clientMsg->sessionId.data = certDataTemp; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); /* 3. When the server receives the client hello message, check the value returned by the HITLS_Accept * interface. */ ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_REC_RECORD_OVERFLOW); ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); parseLen = 0; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_RECORD_OVERFLOW); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC002 * @spec - * @title Verify that the client receives a serverhello message with the length of 2 ^ 14 + 1. The client is expected to * return an alert message. * @precon nan * @brief 1. Create a config and server connection, and construct a server hello message with the length of 2 ^ 14 + 1. * Expected result 1 is obtained. * 2. The client invokes the HITLS_Connect interface. (Expected result 2) * @expect 1. A success message is returned. * 2. A failure message is returned. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MSGLENGTH_TOOLONG_FUNC_TC002(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* 1. Create a config and server connection, and construct a server hello message with the length of 2 ^ 14 + 1. */ uint8_t *certDataTemp = (uint8_t *)BSL_SAL_Calloc(1, (uint32_t)BUF_TOOLONG_LEN); ASSERT_TRUE(certDataTemp != NULL); BSL_SAL_FREE(frameMsg.body.hsMsg.body.serverHello.randomValue.data); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->randomValue.state = ASSIGNED_FIELD; serverMsg->randomValue.size = BUF_TOOLONG_LEN; serverMsg->randomValue.data = certDataTemp; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_TRUE(testInfo.client->ssl != NULL); /* 2. The client invokes the HITLS_Connect interface. */ ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_RECORD_OVERFLOW); ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); parseLen = 0; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_RECORD_OVERFLOW); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ int32_t STUB_HS_DoHandshake_Fatal(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t plainLen) { (void)recordType; (void)data; (void)plainLen; ctx->method.sendAlert(ctx, ALERT_LEVEL_WARNING, ALERT_UNEXPECTED_MESSAGE); /* sends a fatal alert message.*/ return HITLS_INTERNAL_EXCEPTION; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ALERT_DESCRIPTION_FUNC_TC001 * @spec All the alerts listed in Section 6.2 MUST be sent with AlertLevel=fatal and MUST be treated as error alerts * when received regardless of the AlertLevel in the message. * Unknown Alert types MUST be treated as error alerts. * @title If the AlertLevel field in the alarm message received by the client is non-critical but the alarm type is * critical, the client immediately closes the connection. * @precon nan * @brief 6. Alert Protocol row208 * If the AlertLevel field in the alarm message received by the client is not critical but the alarm type is * critical, the connection is closed immediately. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ALERT_DESCRIPTION_FUNC_TC001() { FRAME_Init(); STUB_Init(); FuncStubInfo tmpRpInfo = {0}; HITLS_Config *tlsConfig = HITLS_CFG_NewTLSConfig(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig, 0x00000030U); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); server->ssl->recCtx->outBuf->end = 0; STUB_Replace(&tmpRpInfo, HS_DoHandshake, STUB_HS_DoHandshake_Fatal); int32_t ret = HITLS_Accept(server->ssl); ASSERT_EQ(ret, HITLS_REC_NORMAL_IO_BUSY); STUB_Reset(&tmpRpInfo); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ALERT_DESCRIPTION_FUNC_TC002 * All alerts listed in section 6.2 of the specification must be sent with AlertLevel=Fatal and must be treated as * false alerts When received regardless of the AlertLevel in the message. * Unknown alert types must be treated as false alerts. * @title In the alarm message received by the server, if the value of AlertLevel is not critical but the alarm type is * critical, the connection is closed immediately. * @preconan * @short 6. Alert protocol line 208 * In the alarm message received by the server, if the value of AlertLevel is not critical but the alarm type * is critical, the connection is closed immediately. * @expect forward to normal connection establishment @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ALERT_DESCRIPTION_FUNC_TC002() { FRAME_Init(); STUB_Init(); FuncStubInfo tmpRpInfo = {0}; HITLS_Config *tlsConfig = HITLS_CFG_NewTLSConfig(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig, 0x00000030U); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); client->ssl->recCtx->outBuf->end = 0; STUB_Replace(&tmpRpInfo, HS_DoHandshake, STUB_HS_DoHandshake_Fatal); int32_t ret = HITLS_Connect(client->ssl); ASSERT_EQ(ret, HITLS_REC_NORMAL_IO_BUSY); STUB_Reset(&tmpRpInfo); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); ioUserData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERROR_ENUM_FUNC_TC001 * @spec Peers which receive a message which is syntactically correct but semantically invalid * (e.g., a DHE share of p - 1, or an invalid enum) MUST terminate the connection with * an "illegal_parameter" alert. * @title When the client receives a server keyexchange message in which the value of type is invalid, the client * generates an illegal_parameter alarm and the handshake fails. * @precon nan * @brief 6. Alert Protocol row210 * When the client receives a server keyexchange message in which the value of type is invalid, the client * generates an illegal_parameter alarm and the handshake fails. * @expect Sending an alarm @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERROR_ENUM_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); tlsConfig->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_KEY_EXCHANGE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, SERVER_KEY_EXCHANGE, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); sendBuf[9] = 0x04; ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Accept(clientTlsCtx), HITLS_PARSE_UNSUPPORT_KX_CURVE_TYPE); ALERT_Info alert = {0}; ALERT_GetInfo(server->ssl, &alert); ASSERT_NE(alert.level, ALERT_LEVEL_FATAL); ASSERT_NE(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC001 * @spec - * @title To verify that the server receives a 0-length client hello and is expected to return an alarm. * @precon nan * @brief 1.Create a config and client connection, and construct a 0-length client hello. Expected result 1 is displayed. * 2.The client invokes the HITLS_Connect interface. Expected result 2 is obtained. * @expect 1. Return success * 2.Return failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_CLIENT_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = false; ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == HITLS_SUCCESS); /* Obtain the message buffer */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); recvBuf[6] = 00; recvBuf[7] = 00; recvBuf[8] = 00; recvLen = 6; /* Invoke the test interface. Expected success in receiving and processing, and send Alert. */ ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), HITLS_PARSE_INVALID_MSG_LEN); /* Obtain the message buffer. */ ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); /* Parse to msg structure */ uint32_t parseLen = 0; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Determine whether it is consistent with the expectation. */ ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_DECODE_ERROR); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC002 * @spec - * @title To verify that the client receives a 0-length server hello and returns an alert message. * @precon nan * @brief 1.Create a config and server connection, and construct a 0-length server hello. Expected result 1 is displayed. 2.The client invokes the HITLS_Connect interface. Expected result 2 is obtained. * @expect 1.Return success 2.Return failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC002(void) { HandshakeTestInfo testInfo = {0}; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; testInfo.state = TRY_RECV_SERVER_HELLO; testInfo.isSupportExtendMasterSecret = true; testInfo.isClient = true; ASSERT_TRUE(DefaultCfgStatusParkWithSuite_1_3(&testInfo) == HITLS_SUCCESS); /* Obtain the message buffer. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); recvBuf[6] = 00; recvBuf[7] = 00; recvBuf[8] = 00; recvLen = 6; /* Invoke the test interface. Expected success in receiving and processing, and send Alert. */ ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_PARSE_INVALID_MSG_LEN); /* Obtain the message buffer. */ ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); /* Parse to msg structure */ uint32_t parseLen = 0; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Determine whether it is consistent with the expectation. */ ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_DECODE_ERROR); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); FRAME_DeRegCryptMethod(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_1.c
C
unknown
156,987
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "bsl_sal.h" #include "tls.h" #include "hlt.h" #include "hlt_type.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "process.h" #include "securec.h" #include "session_type.h" #include "rec_wrapper.h" #include "common_func.h" #include "conn_init.h" #include "hs_extensions.h" #include "hitls_crypt_init.h" #include "alert.h" #include "record.h" #include "hs_kx.h" #include "bsl_log.h" #include "cert_callback.h" /* END_HEADER */ #define PORT 23456 #define READ_BUF_SIZE (18 * 1024) #define ALERT_BODY_LEN 2u typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; // Set the session to the client for session recovery. HITLS_TicketKeyCb serverKeyCb; } ResumeTestInfo; typedef struct{ char *ClientCipherSuite; char *ServerCipherSuite; char *ClientGroup; char *ServerGroup; uint8_t ClientKeyExchangeMode; uint8_t ServerKeyExchangeMode; uint8_t psk[PSK_MAX_LEN]; bool SetNothing; bool SuccessOrFail; } SetInfo; void SetConfig(HLT_Ctx_Config *clientconfig, HLT_Ctx_Config *serverconfig, SetInfo setInfo) { if ( !setInfo.SetNothing ) { // Configure the server configuration. if (setInfo.ServerCipherSuite != NULL) { HLT_SetCipherSuites(serverconfig, setInfo.ServerCipherSuite); } if (setInfo.ServerGroup != NULL) { HLT_SetGroups(serverconfig, setInfo.ServerGroup); } memcpy_s(serverconfig->psk, PSK_MAX_LEN, setInfo.psk, sizeof(setInfo.psk)); if ( (setInfo.ClientKeyExchangeMode & (TLS13_KE_MODE_PSK_WITH_DHE | TLS13_KE_MODE_PSK_ONLY)) != 0) { clientconfig->keyExchMode = setInfo.ClientKeyExchangeMode; } // Configure the client configuration. if (setInfo.ClientCipherSuite != NULL) { HLT_SetCipherSuites(clientconfig, setInfo.ClientCipherSuite); } if (setInfo.ClientGroup != NULL) { HLT_SetGroups(clientconfig, setInfo.ClientGroup); } memcpy_s(clientconfig->psk, PSK_MAX_LEN, setInfo.psk, sizeof(setInfo.psk)); if ( (setInfo.ServerKeyExchangeMode & (TLS13_KE_MODE_PSK_WITH_DHE | TLS13_KE_MODE_PSK_ONLY)) != 0) { serverconfig->keyExchMode = setInfo.ServerKeyExchangeMode; } } } static int32_t DoHandshake(ResumeTestInfo *testInfo) { /* Construct a connection. */ testInfo->client = FRAME_CreateLink(testInfo->c_config, testInfo->uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } if (testInfo->clientSession != NULL) { int32_t ret = HITLS_SetSession(testInfo->client->ssl, testInfo->clientSession); if (ret != HITLS_SUCCESS) { return ret; } } testInfo->server = FRAME_CreateLink(testInfo->s_config, testInfo->uioType); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } return FRAME_CreateConnection(testInfo->client, testInfo->server, true, HS_STATE_BUTT); } void ClientCreatConnectWithPara(HLT_FrameHandle *handle, SetInfo setInfo) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; // Create a process. localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // The local client and remote server listen on the TLS connection. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the config file. SetConfig(clientConfig, serverConfig, setInfo); // Listening connection. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); // Configure the interface for constructing abnormal messages. handle->ctx = clientRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Establish a connection. if ( setInfo.SuccessOrFail ) { ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) == 0); }else { ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) != 0); } EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void ServerCreatConnectWithPara(HLT_FrameHandle *handle, SetInfo setInfo) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; // Create a process. localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // The local client and remote server listen on the TLS connection. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the config file. SetConfig(clientConfig, serverConfig, setInfo); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Insert abnormal message callback. handle->ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Client listening connection. clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientConfig, NULL); if ( setInfo.SuccessOrFail ) { ASSERT_TRUE(clientRes != NULL); }else { ASSERT_TRUE(clientRes == NULL); } EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void ResumeConnectWithPara(HLT_FrameHandle *handle, SetInfo setInfo) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; int32_t cnt = 1; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); // Apply for the config context. void *clientConfig = HLT_TlsNewCtx(TLS1_3); ASSERT_TRUE(clientConfig != NULL); // Configure the session restoration function. HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, TLS1_3, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, TLS1_3, false); #endif ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (cnt == 2) { SetConfig(clientCtxConfig, serverCtxConfig, setInfo); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); } DataChannelParam channelParam; channelParam.port = PORT; channelParam.type = TCP; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = TCP; localProcess->connType = TCP; // The server applies for the context. int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = TCP; // Set the FD. ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); // Client, applying for context void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = TCP; // Set the FD. HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { handle->ctx = clientSsl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); if(!setInfo.SuccessOrFail){ ASSERT_TRUE(HLT_TlsConnect(clientSsl) != 0); }else { ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); } } else { // Negotiation ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); // Data read/write ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); // Disable the connection. ASSERT_TRUE(HLT_RpcTlsClose(remoteProcess, serverSslId) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_HasTicket(session) == true); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); }cnt++; } while (cnt < 3); // Perform the connection twice. EXIT: HITLS_SESS_Free(session); HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } static void Test_ServerAddKeyExchangeMode(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { // Add the KeyExchangeMode extension to server hello. (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); uint8_t pskMode[] = {0, 0x2d, 0, 2, 1, 1}; frameMsg.body.hsMsg.length.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.length.data += sizeof(pskMode); frameMsg.body.hsMsg.body.serverHello.extensionLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.extensionLen.data = frameMsg.body.hsMsg.body.serverHello.extensionLen.data + sizeof(pskMode); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); ASSERT_EQ(memcpy_s(&data[*len], bufSize - *len, &pskMode, sizeof(pskMode)), EOK); *len += sizeof(pskMode); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Server_KeyShare_Miss(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { // The keyshare extension of server hello is lost. (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.keyShare.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Client_MasterSecret_Miss(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { // The MasterSecret extension of client hello is lost. (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.extendedMasterSecret.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Client_ObfuscatedTicketAge_NotZero(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { // The value of ObfuscatedTicketAge is not 0 for the external preset PSK. (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.psks.identities.data->obfuscatedTicketAge.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.psks.identities.data->obfuscatedTicketAge.data = 2; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Client_ObfuscatedTicketAge_Zero(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { // The value of ObfuscatedTicketAge is 0 for the PSK generated by the session. (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.psks.identities.data->obfuscatedTicketAge.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.psks.identities.data->obfuscatedTicketAge.data = 0; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Client_Binder_Unnormal(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { // Change the binder value of the psk extension of the client hello message. (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); uint8_t binder[] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,}; frameMsg.body.hsMsg.body.clientHello.psks.binders.data->binder.state = ASSIGNED_FIELD; memcpy_s(frameMsg.body.hsMsg.body.clientHello.psks.binders.data->binder.data, PSK_MAX_LEN, binder, sizeof(binder)); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void FrameCallBack_ServerHello_KeyShare_Add(void *msg, void *userData) { // ServerHello exception: The sent ServerHello message carries the keyshare extension. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ServerHelloMsg *serverhello = &frameMsg->body.hsMsg.body.serverHello; serverhello->keyShare.exState = INITIAL_FIELD; serverhello->keyShare.exLen.state = INITIAL_FIELD; serverhello->keyShare.data.state = INITIAL_FIELD; serverhello->keyShare.data.group.state = ASSIGNED_FIELD; serverhello->keyShare.data.group.data = HITLS_EC_GROUP_SECP256R1; FRAME_ModifyMsgInteger(HS_EX_TYPE_KEY_SHARE, &serverhello->keyShare.exType); uint8_t uu[] = {0x00, 0x15, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56, 0x56}; FRAME_ModifyMsgArray8(uu, sizeof(uu), &serverhello->keyShare.data.keyExchange, &serverhello->keyShare.data.keyExchangeLen); EXIT: return; } static void FrameCallBack_ClientHello_PskExchangeMode_Miss(void *msg, void *userData) { // ClientHello exception: The sent ClientHello message causes the Psk_Exchange_Mode extension to be lost. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ClientHelloMsg *clienthello = &frameMsg->body.hsMsg.body.clientHello; clienthello->pskModes.exState = MISSING_FIELD; EXIT: return; } static void FrameCallBack_ClientHello_KeyShare_Miss(void *msg, void *userData) { // ClientHello exception: The KeyShare extension of the ClientHello message is lost. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ClientHelloMsg *clienthello = &frameMsg->body.hsMsg.body.clientHello; clienthello->keyshares.exState = MISSING_FIELD; EXIT: return; } /** @ * @test UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC001 * @brief 2.1-Incorrect DHE Share-6 * @spec If no common cryptographic parameters can be negotiated, the server MUST abort the handshake with an * appropriate alert. * @title The server sends an hrr message to request the key_share. The negotiation succeeds. * @precon nan * @brief * 1. Set the group (HITLS_EC_GROUP_SECP256R1 and HITLS_EC_GROUP_SECP384R1) on the client and set the group * (HITLS_EC_GROUP_SECP384R1) on the server. Expected result 1 is obtained. * 2. Establish a connection, stop the server in the TRY_SEND_HELLO_RETRY_REQUEST state, and check whether the value of * the group field is HITLS_EC_GROUP_SECP384R1. (Expected result 2) * 3. Continue to establish the connection. Expected result 3 is obtained. * @expect * 1. The setting is successful. * 2. The value of the group field is HITLS_EC_GROUP_SECP384R1. * 3. The connection is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC001() { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *clientconfig = NULL; HITLS_Config *serverconfig = NULL; clientconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(clientconfig != NULL); serverconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(serverconfig != NULL); // Set the group (HITLS_EC_GROUP_SECP256R1 and HITLS_EC_GROUP_SECP384R1) on the client and set the group // (HITLS_EC_GROUP_SECP384R1) on the server. uint16_t clientgroups[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; uint16_t servergroups[] = {HITLS_EC_GROUP_SECP384R1}; ASSERT_EQ(HITLS_CFG_SetGroups(clientconfig, clientgroups, sizeof(clientgroups) / sizeof(uint16_t)), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetGroups(serverconfig, servergroups, sizeof(servergroups) / sizeof(uint16_t)), HITLS_SUCCESS); client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_IO_BUSY); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // Establish a connection, stop the server in the TRY_SEND_HELLO_RETRY_REQUEST state, and check whether the value of // the group field is HITLS_EC_GROUP_SECP384R1. FRAME_ServerHelloMsg *Hello_Retry_RequestMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(Hello_Retry_RequestMsg->keyShare.data.group.data == HITLS_EC_GROUP_SECP384R1); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_SEND_CLIENT_HELLO), HITLS_SUCCESS); // Continue to establish the connection. ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(clientconfig); HITLS_CFG_FreeConfig(serverconfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC002 * @brief 2.1-Incorrect DHE Share-6 * @spec If no common cryptographic parameters can be negotiated, the server MUST abort the handshake with an * appropriate alert. * @title The server receives two unsupported key_share messages. * @precon nan * @brief * 1. Set the group (HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1, and HITLS_EC_GROUP_SECP521R1) on the client and * set the group (HITLS_EC_GROUP_SECP384R1) on the server. Expected result 1 is obtained. * 2. Establish a connection, stop the server in TRY_SEND_HELLO_RETRY_REQUEST state, and change the value of the group * field in the connection to HITLS_EC_GROUP_SECP521R1. Expected result 2 is obtained. * 3. Continue to establish a connection and observe the connection establishment result. Expected result 3 is obtained. * @expect * 1. The setting is successful. * 2. The modification is successful. * 3. The server sends a request again, and the client returns HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC002() { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *clientconfig = NULL; HITLS_Config *serverconfig = NULL; clientconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(clientconfig != NULL); serverconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(serverconfig != NULL); // Set the group (HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1, and HITLS_EC_GROUP_SECP521R1) on the client // and set the group (HITLS_EC_GROUP_SECP384R1) on the server. uint16_t clientgroups[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1, HITLS_EC_GROUP_SECP521R1}; uint16_t servergroups[] = {HITLS_EC_GROUP_SECP384R1}; ASSERT_EQ(HITLS_CFG_SetGroups(clientconfig, clientgroups, sizeof(clientgroups) / sizeof(uint16_t)), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetGroups(serverconfig, servergroups, sizeof(servergroups) / sizeof(uint16_t)), HITLS_SUCCESS); client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recBuf = ioUserData->recMsg.msg; uint32_t recLen = ioUserData->recMsg.len; ASSERT_TRUE(recLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recBuf, recLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // Establish a connection, stop the server in TRY_SEND_HELLO_RETRY_REQUEST state, and change the value of the group // field in the connection to HITLS_EC_GROUP_SECP521R1. FRAME_ServerHelloMsg *Hello_Retry_RequestMsg = &frameMsg.body.hsMsg.body.serverHello; Hello_Retry_RequestMsg->keyShare.data.group.state = ASSIGNED_FIELD; Hello_Retry_RequestMsg->keyShare.data.group.data = HITLS_EC_GROUP_SECP521R1; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_EQ(HITLS_Connect(client->ssl) , HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl) , HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Connect(client->ssl) , HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); // Continue to establish a connection and observe the connection establishment result. ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl) , HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(clientconfig); HITLS_CFG_FreeConfig(serverconfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC003 * @brief 2.1-Incorrect DHE Share-6 * @spec If no common cryptographic parameters can be negotiated, the server MUST abort the handshake with an * appropriate alert. * @title The client receives the key_share with the same elliptic curve for the second time. * @precon nan * @brief * 1. Set the group (HITLS_EC_GROUP_SECP256R1 and HITLS_EC_GROUP_SECP384R1) on the client and set the group * (HITLS_EC_GROUP_SECP384R1) on the server. Expected result 1 is obtained. * 2. Establish a connection, stop the server in the TRY_SEND_HELLO_RETRY_REQUEST state, and change the value of the * group field to HITLS_EC_GROUP_SECP256R1. Expected result 2 is obtained. * 3. Continue connection establishment and observe the connection establishment result. Expected result 3 is obtained. * @expect * 1. The setting is successful. * 2. The modification is successful. * 3. The connection fails to be established. After receiving the request message, the client returns * HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC003() { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *clientconfig = NULL; HITLS_Config *serverconfig = NULL; clientconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(clientconfig != NULL); serverconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(serverconfig != NULL); // Set the group (HITLS_EC_GROUP_SECP256R1 and HITLS_EC_GROUP_SECP384R1) on the client and set the group // (HITLS_EC_GROUP_SECP384R1) on the server. uint16_t clientgroups[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; uint16_t servergroups[] = {HITLS_EC_GROUP_SECP384R1}; ASSERT_EQ(HITLS_CFG_SetGroups(clientconfig, clientgroups, sizeof(clientgroups) / sizeof(uint16_t)), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetGroups(serverconfig, servergroups, sizeof(servergroups) / sizeof(uint16_t)), HITLS_SUCCESS); client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recBuf = ioUserData->recMsg.msg; uint32_t recLen = ioUserData->recMsg.len; ASSERT_TRUE(recLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recBuf, recLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // Establish a connection, stop the server in the TRY_SEND_HELLO_RETRY_REQUEST state, and change the value of the // group field to HITLS_EC_GROUP_SECP256R1. FRAME_ServerHelloMsg *Hello_Retry_RequestMsg = &frameMsg.body.hsMsg.body.serverHello; Hello_Retry_RequestMsg->keyShare.data.group.state = ASSIGNED_FIELD; Hello_Retry_RequestMsg->keyShare.data.group.data = HITLS_EC_GROUP_SECP256R1; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_EQ(HITLS_Connect(client->ssl) , HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(clientconfig); HITLS_CFG_FreeConfig(serverconfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC004 * @brief 2.1-Incorrect DHE Share-6 * @spec If no common cryptographic parameters can be negotiated, the server MUST abort the handshake with an * appropriate alert. * @title The client receives an unsupported elliptic curve key_share request. * @precon nan * @brief * 1. Set the group (HITLS_EC_GROUP_SECP256R1 and HITLS_EC_GROUP_SECP384R1) on the client and set the group * (HITLS_EC_GROUP_SECP384R1) on the server. Expected result 1 is obtained. * 2. Establish a connection, stop the server in the TRY_SEND_HELLO_RETRY_REQUEST state, and change the value of the * group field to HITLS_EC_GROUP_SECP521R1. Expected result 2 is obtained. * 3. Continue connection establishment and observe the connection establishment result. Expected result 3 is obtained. * @expect * 1. The setting is successful. * 2. The modification is successful. * 3. The connection fails to be established. After receiving the request message, the client returns * HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC004() { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *clientconfig = NULL; HITLS_Config *serverconfig = NULL; clientconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(clientconfig != NULL); serverconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(serverconfig != NULL); // Set the group (HITLS_EC_GROUP_SECP256R1 and HITLS_EC_GROUP_SECP384R1) on the client and set the group // (HITLS_EC_GROUP_SECP384R1) on the server. uint16_t clientgroups[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; uint16_t servergroups[] = {HITLS_EC_GROUP_SECP384R1}; ASSERT_EQ(HITLS_CFG_SetGroups(clientconfig, clientgroups, sizeof(clientgroups) / sizeof(uint16_t)), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetGroups(serverconfig, servergroups, sizeof(servergroups) / sizeof(uint16_t)), HITLS_SUCCESS); client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recBuf = ioUserData->recMsg.msg; uint32_t recLen = ioUserData->recMsg.len; ASSERT_TRUE(recLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recBuf, recLen, &frameMsg, &parseLen) == HITLS_SUCCESS); // Establish a connection, stop the server in the TRY_SEND_HELLO_RETRY_REQUEST state, and change the value of the // group field to HITLS_EC_GROUP_SECP521R1. FRAME_ServerHelloMsg *Hello_Retry_RequestMsg = &frameMsg.body.hsMsg.body.serverHello; Hello_Retry_RequestMsg->keyShare.data.group.state = ASSIGNED_FIELD; Hello_Retry_RequestMsg->keyShare.data.group.data = HITLS_EC_GROUP_SECP521R1; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); // Continue connection establishment and observe the connection establishment result. ASSERT_EQ(HITLS_Connect(client->ssl) , HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(clientconfig); HITLS_CFG_FreeConfig(serverconfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC005 * @brief 2.1. Incorrect DHE Share * @spec If the client has not provided a sufficient "key_share" extension (e.g., it includes only DHE or ECDHE groups unacceptable to or unsupported by the server), the server corrects the mismatch with a HelloRetryRequest and the client needs to restart the handshake with an appropriate "key_share" extension, as shown in Figure 2. If no common cryptographic parameters can be negotiated, the server MUST abort the handshake with an appropriate alert. * @title Configure groups_list:"brainpoolP512r1:X25519" on the client and groups_list:"brainpoolP512r1:X25519" on the server. Observe the link setup result and check whether the server sends Hello_Retry_Requset. * @precon nan * @brief 1. Configure groups_list:"brainpoolP512r1:X25519" on the client and groups_list:"brainpoolP512r1:X25519" on the server. * @expect 1. Send clienthello with X25519 keyshare. The link is established successfully. 2. The server does not send Hello_Retry_Requset. * @prior Level 2 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_CONSISTENCY_RFC8446_REQUEST_CLIENT_HELLO_FUNC_TC005() { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *clientconfig = NULL; HITLS_Config *serverconfig = NULL; clientconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(clientconfig != NULL); serverconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(serverconfig != NULL); uint16_t clientgroups[] = {HITLS_EC_GROUP_BRAINPOOLP512R1, HITLS_EC_GROUP_CURVE25519}; uint16_t servergroups[] = {HITLS_EC_GROUP_BRAINPOOLP512R1, HITLS_EC_GROUP_CURVE25519}; ASSERT_EQ(HITLS_CFG_SetGroups(serverconfig, servergroups, sizeof(servergroups)/sizeof(uint16_t)) , HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetGroups(clientconfig, clientgroups, sizeof(clientgroups)/sizeof(uint16_t)) , HITLS_SUCCESS); client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recBuf = ioUserData->recMsg.msg; uint32_t recLen = ioUserData->recMsg.len; ASSERT_TRUE(recLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recBuf, recLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverHello = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverHello->keyShare.data.group.data == HITLS_EC_GROUP_CURVE25519); ASSERT_EQ(server->ssl->hsCtx->haveHrr, false); // Continue to establish the link. ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(clientconfig); HITLS_CFG_FreeConfig(serverconfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_EXCHANGE_MODES_MISS_FUNC_TC001 * @brief 4.2.9-Pre-Shared Key Exchange Modes-77 * @spec In order to use PSKs, clients MUST also send a "psk_key_exchange_modes" extension. * @title Preset psk Client Lost Pre-Shared Key Exchange Modes Extension * @precon nan * @brief * 1. Preset the psk, modify the client hello message sent by the client to make the psk_key_exchange_modes extension * lost, and observe the server behavior. * @expect * 1. Connect establishment is interrupted. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_EXCHANGE_MODES_MISS_FUNC_TC001() { // Preset the psk, modify the client hello message sent by the client to make the psk_key_exchange_modes extension // lost, and observe the server behavior. SetInfo setInfo = {0}; memcpy_s(setInfo.psk, PSK_MAX_LEN, "12121212121212", sizeof("12121212121212")); setInfo.ClientCipherSuite = "HITLS_AES_128_GCM_SHA256"; setInfo.ClientCipherSuite = "HITLS_AES_128_GCM_SHA256"; setInfo.SuccessOrFail = 0; HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = FrameCallBack_ClientHello_PskExchangeMode_Miss; ClientCreatConnectWithPara(&handle, setInfo); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_EXCHANGE_MODES_MISS_FUNC_TC002 * @brief 4.2.9-Pre-Shared Key Exchange Modes-77 * @spec In order to use PSKs, clients MUST also send a "psk_key_exchange_modes" extension. * @title psk session recovery client lost Pre-Shared Key Exchange Modes extension * @precon nan * @brief * 1. Preset the psk, modify the client hello message sent by the client to make the psk_key_exchange_modes extension lost, and observe the server behavior. * @expect * 1. Connect establishment is interrupted. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_EXCHANGE_MODES_MISS_FUNC_TC002() { // Preset the psk, modify the client hello message sent by the client to make the psk_key_exchange_modes extension // lost, and observe the server behavior. SetInfo setInfo = {0}; setInfo.SetNothing = 1; setInfo.SuccessOrFail = 0; HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = FrameCallBack_ClientHello_PskExchangeMode_Miss; ResumeConnectWithPara(&handle, setInfo); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_EXCHANGE_MODES_ADD_FUNC_TC001 * @brief 4.2.9-Pre-Shared Key Exchange Modes-80 * @spec The server MUST NOT send a "psk_key_exchange_modes" extension. * @title The session restoration server carries psk_key_exchange_modes. * @precon nan * @brief * 1. Establish a connection, save the session, and restore the session. * 2. Modify the server hello message sent by the server to carry the psk_key_exchange_mode extension and observe the * client behavior. * @expect * 1. The connection is successfully established and the session is restored. * 2. The client sends an alert message and disconnects the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_EXCHANGE_MODES_ADD_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; // Establish a connection, save the session, and restore the session. testInfo.s_config = HITLS_CFG_NewTLS13Config(); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); ASSERT_TRUE(testInfo.c_config != NULL); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); // Modify the server hello message sent by the server to carry the psk_key_exchange_mode extension and observe the // client behavior. RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerAddKeyExchangeMode}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_PARSE_UNSUPPORTED_EXTENSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_ADD_FUNC_TC001 * @brief 4.2.9-Pre-Shared Key Exchange Modes-80 * @spec psk_ke: PSK-only key establishment. In this mode, the server MUST NOT supply a "key_share" value. * @title Preset the PSK. In psk_ke mode, the server carries the key_share extension. * @precon nan * @brief * 1. Preset PSK * 2. Set psk_key_exchange_mode to psk_ke on the client and server, * 3. Modify the server hello message sent by the server to carry the key_share extension and observe the client * behavior. * @expect * 1. The setting is successful. * 2. The setting is successful. * 3. The client sends an alert message and disconnects the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_ADD_FUNC_TC001() { // Preset PSK SetInfo setInfo = {0}; memcpy_s(setInfo.psk, PSK_MAX_LEN, "12121212121212", sizeof("12121212121212")); setInfo.ClientCipherSuite = "HITLS_AES_128_GCM_SHA256"; setInfo.ClientCipherSuite = "HITLS_AES_128_GCM_SHA256"; // Set psk_key_exchange_mode to psk_ke on the client and server setInfo.ClientKeyExchangeMode = TLS13_KE_MODE_PSK_ONLY; setInfo.ServerKeyExchangeMode = TLS13_KE_MODE_PSK_ONLY; setInfo.SuccessOrFail = 0; // Modify the server hello message sent by the server to carry the key_share extension and observe the client // behavior. HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; handle.frameCallBack = FrameCallBack_ServerHello_KeyShare_Add; ServerCreatConnectWithPara(&handle, setInfo); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_MISS_FUNC_TC001 * @brief 4.2.9-Pre-Shared Key Exchange Modes-77 * @spec psk_dhe_ke: PSK with (EC)DHE key establishment. In this mode, the * client and server MUST supply "key_share" values as described in Section 4.2.8. * @title Session Recovery Client Lost Key_share Extension * @precon nan * @brief * 1. When the session is recovered, modify the client hello message sent by the client so that the Key_Share extension * is lost. Observe the server behavior. * @expect * 1. Connect establishment is interrupted. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_MISS_FUNC_TC001() { // When the session is recovered, modify the client hello message sent by the client so that the Key_Share extension // is lost. Observe the server behavior. SetInfo setInfo = {0}; setInfo.SetNothing = 1; setInfo.SuccessOrFail = 0; HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = FrameCallBack_ClientHello_KeyShare_Miss; ResumeConnectWithPara(&handle, setInfo); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_MISS_FUNC_TC002 * @brief 4.2.9-Pre-Shared Key Exchange Modes-80 * @spec psk_dhe_ke: PSK with (EC)DHE key establishment. In this mode, the * client and server MUST supply "key_share" values as described in Section 4.2.8. * @title Server: psk_key_exchange_mode: The key_share extension is lost under psk_dhe_ke. * @precon nan * @brief * 1. Preset PSK * 2. Set psk_key_exchange_mode to psk_dhe_ke on the client server, modify the server hello message sent by the server to * lose the key_share extension, and observe the client behavior. * @expect * 1. The setting is successful. * 2. The client sends an alert message to disconnect the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_MISS_FUNC_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Server_KeyShare_Miss }; RegisterWrapper(wrapper); testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); // Preset PSK char psk[] = "aaaaaaaaaaaaaaaa"; ASSERT_TRUE(ExampleSetPsk(psk) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskClientCallback(testInfo.c_config, ExampleClientCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskServerCallback(testInfo.s_config, ExampleServerCb) == HITLS_SUCCESS); // Set psk_key_exchange_mode to psk_dhe_ke on the client server, modify the server hello message sent by the server // to lose the key_share extension, and observe the client behavior. testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_HANDSHAKE_FAILURE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_OBFUSCATED_TICKET_AGE_FUNC_TC001 * @brief 4.2.11-Pre-Shared Key Extension-93 * @spec For identities established externally, an obfuscated_ticket_age of 0 SHOULD be used, and servers MUST ignore * the value * @title The obfuscated_ticket_age of the preset PSK is not 0. * @precon nan * @brief * 1. Preset PSK * 2. Modify the obfuscated_ticket_age field in the psk extension in the client hello message sent by the client to * ensure that the field is not 0. * 3. Establish a connection. * @expect * 1. The setting is successful. * 2. The modification is successful. * 3. The connection is successfully established and certificate authentication is performed. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_OBFUSCATED_TICKET_AGE_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_ObfuscatedTicketAge_NotZero }; RegisterWrapper(wrapper); testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); // Preset PSK char psk[] = "aaaaaaaaaaaaaaaa"; ASSERT_TRUE(ExampleSetPsk(psk) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskClientCallback(testInfo.c_config, ExampleClientCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskServerCallback(testInfo.s_config, ExampleServerCb) == HITLS_SUCCESS); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Modify the obfuscated_ticket_age field in the psk extension in the client hello message sent by the client to // ensure that the field is not 0. ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverhelloMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverhelloMsg->pskSelectedIdentity.exLen.data == 0); // Establish a connection. ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_SEND_CERTIFICATE) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ extern int32_t CompareBinder(TLS_Ctx *ctx, const PreSharedKey *pskNode, uint8_t *psk, uint32_t pskLen, uint32_t truncateHelloLen); static int32_t CompareBinder_Success(TLS_Ctx *ctx, const PreSharedKey *pskNode, uint8_t *psk, uint32_t pskLen, uint32_t truncateHelloLen) { (void)ctx; (void)pskNode; (void)psk; (void)pskLen; (void)truncateHelloLen; return 0; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_OBFUSCATED_TICKET_AGE_FUNC_TC002 * @brief 4.2.11-Pre-Shared Key Extension-93 * @spec For identities established externally, an obfuscated_ticket_age of 0 SHOULD be used, and servers MUST ignore * the value * @title The obfuscated_ticket_age of the PSK generated by the session is 0. * @precon nan * @brief * 1. Preset PSK * 2. Modify the obfuscated_ticket_age field in the psk extension in the client hello message sent by the client to * ensure that the value is not 0. * 3. Establish a connection. * @expect * 1. The setting is successful. * 2. The modification is successful. * 3. Certificate authentication @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_OBFUSCATED_TICKET_AGE_FUNC_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); // Preset PSK ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // Modify the obfuscated_ticket_age field in the psk extension in the client hello message sent by the client to // ensure that the value is not 0. RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_ObfuscatedTicketAge_Zero}; RegisterWrapper(wrapper); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); STUB_Init(); FuncStubInfo stubInfo = {0}; STUB_Replace(&stubInfo, CompareBinder, CompareBinder_Success); // Establish a connection. ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(testInfo.client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 1); EXIT: ClearWrapper(); STUB_Reset(&stubInfo); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_OBFUSCATED_TICKET_AGE_FUNC_TC003 * @brief 4.2.11-Pre-Shared Key Extension-93 * @spec For identities established externally, an obfuscated_ticket_age of 0 SHOULD be used, and servers MUST ignore * the value * @title The obfuscated_ticket_age of the PSK generated by the session is different from the original value. * @precon nan * @brief * 1. Preset PSK * 2. Modify the obfuscated_ticket_age field in the psk extension in the client hello message sent by the client to * ensure that the field is not 0. * 3. Establish a connection. * @expect * 1. The setting is successful. * 2. The modification is successful. * 3. Certificate authentication @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_OBFUSCATED_TICKET_AGE_FUNC_TC003() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); // Preset PSK ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // Modify the obfuscated_ticket_age field in the psk extension in the client hello message sent by the client to // ensure that the field is not 0. RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_ObfuscatedTicketAge_NotZero}; RegisterWrapper(wrapper); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); STUB_Init(); FuncStubInfo stubInfo = {0}; STUB_Replace(&stubInfo, CompareBinder, CompareBinder_Success); // Establish a connection. ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); STUB_Reset(&stubInfo); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ #define SESSION_SZ 10 static HITLS_Session *g_userSession[SESSION_SZ]; static int g_sessionSz = 0; void ClearSessoins() { for (int i = 0; i < g_sessionSz; i++) { HITLS_SESS_Free(g_userSession[i]); } g_sessionSz = 0; } HITLS_Session *GetSession(int index) { if (index < g_sessionSz) { return HITLS_SESS_Dup(g_userSession[index]); } return NULL; } void AddSession(HITLS_Session *session) { if (g_sessionSz < SESSION_SZ - 1) { g_userSession[g_sessionSz] = session; g_sessionSz++; } } int32_t Test_NewSessionCb(HITLS_Ctx *ctx, HITLS_Session *session) { (void)ctx; if (ctx->isClient && HITLS_SESS_IsResumable(session)) { AddSession(session); return 1; } return 0; } static int32_t Test_PskUseSessionCb_WithSHA256(HITLS_Ctx *ctx, uint32_t hashAlgo, const uint8_t **id, uint32_t *idLen, HITLS_Session **session) { (void)ctx; (void)hashAlgo; (void)id; (void)idLen; static uint8_t identity[] = "123456"; if (g_sessionSz > 0) { *id = identity; *idLen = sizeof(identity); *session = GetSession(g_sessionSz - 1); (*session)->cipherSuite = HITLS_AES_128_GCM_SHA256; return HITLS_PSK_USE_SESSION_CB_SUCCESS; } return HITLS_PSK_USE_SESSION_CB_FAIL; } static int32_t Test_PskUseSessionCb_WithSHA384(HITLS_Ctx *ctx, uint32_t hashAlgo, const uint8_t **id, uint32_t *idLen, HITLS_Session **session) { (void)ctx; (void)hashAlgo; (void)id; (void)idLen; static uint8_t identity[] = "123456"; if (g_sessionSz > 0) { *id = identity; *idLen = sizeof(identity); *session = GetSession(g_sessionSz - 1); (*session)->cipherSuite = HITLS_AES_256_GCM_SHA384; return HITLS_PSK_USE_SESSION_CB_SUCCESS; } return HITLS_PSK_USE_SESSION_CB_FAIL; } static int32_t Test_PskUseSessionCb_Default(HITLS_Ctx *ctx, uint32_t hashAlgo, const uint8_t **id, uint32_t *idLen, HITLS_Session **session) { (void)ctx; (void)hashAlgo; (void)id; (void)idLen; static uint8_t identity[] = "123456"; if (g_sessionSz > 0) { *id = identity; *idLen = sizeof(identity); *session = GetSession(g_sessionSz - 1); HITLS_Session *newSession = HITLS_SESS_New(); (*session)->cipherSuite = newSession->cipherSuite; HITLS_SESS_Free(newSession); return HITLS_PSK_USE_SESSION_CB_SUCCESS; } return HITLS_PSK_USE_SESSION_CB_FAIL; } static int32_t Test_PskFindSessionCb_WithSHA256(HITLS_Ctx *ctx, const uint8_t *identity, uint32_t identityLen, HITLS_Session **session) { (void)ctx; (void)identity; (void)identityLen; if (g_sessionSz > 0) { *session = GetSession(g_sessionSz - 1); (*session)->cipherSuite = HITLS_AES_128_GCM_SHA256; return HITLS_PSK_FIND_SESSION_CB_SUCCESS; } return HITLS_PSK_FIND_SESSION_CB_FAIL; } static int32_t Test_PskFindSessionCb_WithSHA384(HITLS_Ctx *ctx, const uint8_t *identity, uint32_t identityLen, HITLS_Session **session) { (void)ctx; (void)identity; (void)identityLen; if (g_sessionSz > 0) { *session = GetSession(g_sessionSz - 1); (*session)->cipherSuite = HITLS_AES_256_GCM_SHA384; return HITLS_PSK_FIND_SESSION_CB_SUCCESS; } return HITLS_PSK_FIND_SESSION_CB_FAIL; } static int32_t Test_PskFindSessionCb_Default(HITLS_Ctx *ctx, const uint8_t *identity, uint32_t identityLen, HITLS_Session **session) { (void)ctx; (void)identity; (void)identityLen; if (g_sessionSz > 0) { *session = GetSession(g_sessionSz - 1); HITLS_Session *newSession = HITLS_SESS_New(); (*session)->cipherSuite = newSession->cipherSuite; HITLS_SESS_Free(newSession); return HITLS_PSK_FIND_SESSION_CB_SUCCESS; } return HITLS_PSK_FIND_SESSION_CB_FAIL; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC001 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec For externally established PSKs, the Hash algorithm MUST be set when the PSK is established or default to * SHA-256 if no such algorithm is defined. The server MUST ensure that it selects a compatible PSK (if any) and * cipher suite. * @title The hash settings on the client and server are inconsistent. * @precon nan * @brief * 1. Preset the PSK. The client invokes HITLS_PskUseSessionCb to set the hash to sha256, and the service invokes * HITLS_PskFindSessionCb to set the hash to sha384. * 2. Connect establishment * @expect * 1. The setting is successful. * 2. Connect establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetNewSessionCb(testInfo.c_config, Test_NewSessionCb); // Preset the PSK. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // The client invokes HITLS_PskUseSessionCb to set the hash to sha256, and the service invokes // HITLS_PskFindSessionCb to set the hash to sha384. HITLS_CFG_SetPskUseSessionCallback(testInfo.c_config, Test_PskUseSessionCb_WithSHA256); HITLS_CFG_SetPskFindSessionCallback(testInfo.s_config, Test_PskFindSessionCb_WithSHA384); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Connect establishment ASSERT_TRUE( FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT) == HITLS_MSG_HANDLE_PSK_INVALID); EXIT: ClearSessoins(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC007 * @test UT_TLS13_RFC8446_PSKHASH_TC001_1 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec For externally established PSKs, the Hash algorithm MUST be set when the PSK is established or default to * SHA-256. if no such algorithm is defined. The server MUST ensure that it selects a compatible PSK (if any) and * cipher suite. * @title The hash settings on the client and server are inconsistent. * @precon nan * @brief * 1. Preset the PSK. The client invokes HITLS_PskUseSessionCb to set the hash to sha384, and the service invokes * HITLS_PskFindSessionCb to set the hash to sha256. * 2. Connect establishment * @expect * 1. The setting is successful. * 2. Connect establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC007() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetNewSessionCb(testInfo.c_config, Test_NewSessionCb); // Preset the PSK. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // The client invokes HITLS_PskUseSessionCb to set the hash to sha384, and the service invokes // HITLS_PskFindSessionCb to set the hash to sha256. HITLS_CFG_SetPskUseSessionCallback(testInfo.c_config, Test_PskUseSessionCb_WithSHA384); HITLS_CFG_SetPskFindSessionCallback(testInfo.s_config, Test_PskFindSessionCb_WithSHA256); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Connect establishment ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_SEND_CERTIFICATE) , HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: ClearSessoins(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC002 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec For externally established PSKs, the Hash algorithm MUST be set when the PSK is established or default to * SHA-256.if no such algorithm is defined. The server MUST ensure that it selects a compatible PSK (if any) and * cipher suite. * @title The hash set does not match the hash of the negotiated cipher suite. * @precon nan * @brief * 1. Preset the PSK. The client and service monotonically use the HITLS_PskUseSessionCb to set the hash to sha256 and * the negotiation cipher suite to sha384. * 2. Connect establishment * @expect * 1. The setting is successful. * 2. If the PSK authentication fails, perform certificate authentication. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetNewSessionCb(testInfo.c_config, Test_NewSessionCb); // Preset the PSK. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // The client and service monotonically use the HITLS_PskUseSessionCb to set the hash to sha256 and the negotiation // cipher suite to sha384. uint16_t cipher_suite[] = {HITLS_AES_256_GCM_SHA384}; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite) / sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite) / sizeof(uint16_t)); HITLS_CFG_SetPskUseSessionCallback(testInfo.c_config, Test_PskUseSessionCb_WithSHA256); HITLS_CFG_SetPskFindSessionCallback(testInfo.s_config, Test_PskFindSessionCb_WithSHA256); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Connect establishment ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_SEND_CERTIFICATE), HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearSessoins(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC003 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec For externally established PSKs, the Hash algorithm MUST be set when the PSK is established or default to * SHA-256.if no such algorithm is defined. The server MUST ensure that it selects a compatible PSK (if any) and * cipher suite. * @title The hash set by the hash matches the hash of the negotiated cipher suite. * @precon nan * @brief * 1. Preset the PSK. Use the HITLS_PskUseSessionCb command to set the hash to sha256 and the negotiation cipher suite to * sha256. * 2. Connect establishment * @expect * 1. The setting is successful. * 2. The connection is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC003() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetNewSessionCb(testInfo.c_config, Test_NewSessionCb); // Preset the PSK. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // Use the HITLS_PskUseSessionCb command to set the hash to sha256 and the negotiation cipher suite to sha256. uint16_t cipher_suite[] = { HITLS_AES_128_GCM_SHA256 }; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetPskUseSessionCallback(testInfo.c_config, Test_PskUseSessionCb_WithSHA256); HITLS_CFG_SetPskFindSessionCallback(testInfo.s_config, Test_PskFindSessionCb_WithSHA256); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Connect establishment ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recBuf = ioUserData->recMsg.msg; uint32_t recLen = ioUserData->recMsg.len; ASSERT_TRUE(recLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recBuf, recLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *ServerHello = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(ServerHello->pskSelectedIdentity.data.data == 0); ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: ClearSessoins(); FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC004 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec For externally established PSKs, the Hash algorithm MUST be set when the PSK is established or default to * SHA-256 if no such algorithm is defined. The server MUST ensure that it selects a compatible PSK (if any) and * cipher suite. * @title The default client hash is sha256. * @precon nan * @brief * 1. Preset the PSK. The client does not set the hash algorithm. The server sets the hash algorithm to 256 and the * negotiation cipher suite to sha256. * 2. Establish a connection and check the hash algorithm on the client. * @expect * 1. The setting is successful. * 2. The connection is set up successfully, and the hash algorithm on the client is 256. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC004() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetNewSessionCb(testInfo.c_config, Test_NewSessionCb); uint16_t cipher_suite[] = { HITLS_AES_128_GCM_SHA256 }; // Preset the PSK. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // The client does not set the hash algorithm. The server sets the hash algorithm to 256 and the negotiation cipher // suite to sha256. HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite) / sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite) / sizeof(uint16_t)); HITLS_CFG_SetPskUseSessionCallback(testInfo.c_config, Test_PskUseSessionCb_Default); HITLS_CFG_SetPskFindSessionCallback(testInfo.s_config, Test_PskFindSessionCb_WithSHA256); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Establish a connection and check the hash algorithm on the client. ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_SEND_CERTIFICATE) != HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC005 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec For externally established PSKs, the Hash algorithm MUST be set when the PSK is established or default to * SHA-256.if no such algorithm is defined. The server MUST ensure that it selects a compatible PSK (if any) and * cipher suite. * @title The default hash on the server is sha256. * @precon nan * @brief * 1. Preset the PSK. The server does not set the hash algorithm. The client sets the hash algorithm to 256 and the * negotiation cipher suite to sha256. * 2. Establish a connection and check the hash algorithm on the server. * @expect * 1. The setting is successful. * 2. The connection is set up successfully, and the hash algorithm on the server is 256. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC005() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetNewSessionCb(testInfo.c_config, Test_NewSessionCb); uint16_t cipher_suite[] = { HITLS_AES_128_GCM_SHA256 }; // Preset the PSK. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // The server does not set the hash algorithm. The client sets the hash algorithm to 256 and the negotiation cipher // suite to sha256. HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite) / sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite) / sizeof(uint16_t)); HITLS_CFG_SetPskUseSessionCallback(testInfo.c_config, Test_PskUseSessionCb_WithSHA256); HITLS_CFG_SetPskFindSessionCallback(testInfo.s_config, Test_PskFindSessionCb_Default); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Establish a connection and check the hash algorithm on the server. ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_SEND_CERTIFICATE) != HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC006 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec For externally established PSKs, the Hash algorithm MUST be set when the PSK is established or default to * SHA-256.if no such algorithm is defined. The server MUST ensure that it selects a compatible PSK (if any) and * cipher suite. * @title The hash setting is inconsistent with the negotiated cipher suite. * @precon nan * @brief * 1. The client invokes the HITLS_PskClientCb interface to set the preset PSK. The server invokes the HITLS_PskClientCb * interface to set the preset PSK. * 2. The algorithm suite negotiation result is 384, * 3. Establish a connection. * @expect * 1. The setting is successful. * 2. The setting is successful. * 3. The connection is successfully established and certificate authentication is performed. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKHASH_FUNC_TC006() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); // The client invokes the HITLS_PskClientCb interface to set the preset PSK. The server invokes the HITLS_PskClientCb interface to set the preset PSK. char psk[] = "aaaaaaaaaaaaaaaa"; ASSERT_TRUE(ExampleSetPsk(psk) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskClientCallback(testInfo.c_config, ExampleClientCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetPskServerCallback(testInfo.s_config, ExampleServerCb) == HITLS_SUCCESS); // The algorithm suite negotiation result is 384 uint16_t cipher_suite[] = { HITLS_AES_256_GCM_SHA384 }; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); // Establish a connection. ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_SEND_CERTIFICATE) , HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKBINDER_FUNC_TC001 * @brief 4.2.11-Pre-Shared Key Extension-97 * @spec the server MUST validate the corresponding binder value (see Section 4.2.11.2 below). * If this value is not present or does not validate, the server MUST abort the handshake. * @title Modify the binder of client hello to make the server verification fail. * @precon nan * @brief * 1. The connection is established and the session is restored. * 2. Change the value of binder in the psk extension of the client hello message sent by the client, and observe the * behavior on the server. * @expect * 1. The setting is successful. * 2. The server terminates the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKBINDER_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); // The connection is established and the session is restored. testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // Change the value of binder in the psk extension of the client hello message sent by the client, and observe the // behavior on the server. RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_Binder_Unnormal}; RegisterWrapper(wrapper); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_PSK_INVALID); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKBINDER_FUNC_TC003 * @brief 4.2.11-Pre-Shared Key Extension-97 * @spec the server MUST validate the corresponding binder value (see Section 4.2.11.2 below). * If this value is not present or does not validate, the server MUST abort the handshake. * @title Modify the client hello message so that the server fails to verify the binder. * @precon nan * @brief * 1. The connection is established and the session is restored. * 2. Discard the master_secret extension of the client hello message sent by the client and observe the behavior of the * server. * @expect * 1. The setting is successful. * 2. The server terminates the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKBINDER_FUNC_TC003() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); // The connection is established and the session is restored. testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // Discard the master_secret extension of the client hello message sent by the client and observe the behavior of // the server. RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_MasterSecret_Miss}; RegisterWrapper(wrapper); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); ASSERT_EQ( FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_PSK_INVALID); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECODE_VERSION_FUNC_TC001 * @brief 4.2.11-Pre-Shared Key Extension-97 * @spec Implementations MUST NOT send any records with a version less than 0x0300. * Implementations SHOULD NOT accept any records with a version less than 0x0300 * @title The server receives a client hello message whose recode version is 0x0300/0x0200. * @precon nan * @brief * 1. Change the recode version of the client hello message sent by the client to 0x0300/0x0200. * 2. Observe the server behavior. * @expect * 1. The setting is successful. * 2. Connect establishment success/failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECODE_VERSION_FUNC_TC001(int value, int expect) { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_RECV_CLIENT_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); /* Change the recode version of the client hello message sent by the client to 0x0300/0x0200. */ uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); frameMsg.recVersion.data = value; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); /* Observe the server behavior. */ ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Accept(testInfo.server->ssl), expect); EXIT: HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECODE_VERSION_FUNC_TC002 * @brief 4.2.11-Pre-Shared Key Extension-97 * @spec Implementations MUST NOT send any records with a version less than 0x0300. * Implementations SHOULD NOT accept any records with a version less than 0x0300 * @title The client receives the server hello message whose recode version is 0x0300/0x0200. * @precon nan * @brief * 1. Change the recode version of the client hello message sent by the server to 0x0300/0x0200. * 2. Observe client behavior. * @expect * 1. The setting is successful. * 2. Connect establishment success/failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECODE_VERSION_FUNC_TC002(int value, int expect) { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); /* Change the recode version of the client hello message sent by the server to 0x0300/0x0200. */ uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); frameMsg.recVersion.data = value; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(testInfo.client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); /* Observe client behavior. */ ASSERT_TRUE(testInfo.server->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), expect); EXIT: HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC001 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec * @title Two PSKs. Select the first one when the conditions are met. * @precon nan * @brief * 1. The PSK is generated during connection establishment, and set to the client. * 2. Preset the PSK and establish a connection. * @expect * 1. The setting is successful. * 2. The connection is successfully set up and the first PSK is selected. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); uint16_t cipher_suite[] = { HITLS_AES_128_GCM_SHA256 }; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // The PSK is generated during connection establishment, and set to the client. HITLS_CFG_SetPskClientCallback(testInfo.c_config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.s_config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO) , HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Preset the PSK and establish a connection. */ FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverMsg->pskSelectedIdentity.exLen.data != 0); ASSERT_TRUE(serverMsg->pskSelectedIdentity.data.data == 0); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_SESS_Free(testInfo.clientSession); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC002 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec * @title Two psks. If the former one does not meet the requirements, select the second one. * @precon nan * @brief * 1. The PSK is generated during connection establishment. Configure the default 384 algorithm suite on the client. * 2. Set the 256 cipher suite, preset the PSK, and establish a connection. * @expect * 1. The setting is successful. * 2. The connection is successfully established and the second cipher suite is selected. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); // The PSK is generated during connection establishment. Configure the default 384 algorithm suite on the client. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; /* Set the 256 cipher suite, preset the PSK, and establish a connection. */ uint16_t cipher_suite[] = { HITLS_AES_128_GCM_SHA256, HITLS_AES_256_GCM_SHA384 }; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite[0])/sizeof(uint16_t)); HITLS_CFG_SetPskClientCallback(testInfo.c_config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.s_config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO) , HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverMsg->pskSelectedIdentity.exLen.data != 0); ASSERT_TRUE(serverMsg->pskSelectedIdentity.data.data == 1); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_SESS_Free(testInfo.clientSession); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC003 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec * @title Neither of the two PSKs meets the requirements. Select certificate authentication. * @precon nan * @brief * 1. Set the 256 algorithm suite and set up a connection to generate a PSK, and set to the client. * 2. Set the 384 algorithm suite, preset the PSK, and establish a connection. * @expect * 1. The setting is successful. * 2. The connection is successfully established and the PSK authentication is performed. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC003() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); // Set the 256 algorithm suite and set up a connection to generate a PSK, and set to the client. uint16_t cipher_suite[] = { HITLS_AES_128_GCM_SHA256 }; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // Set the 384 algorithm suite, preset the PSK, and establish a connection. cipher_suite[0] = HITLS_AES_256_GCM_SHA384; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetPskClientCallback(testInfo.c_config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.s_config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO) , HITLS_SUCCESS); /* Obtain the message buffer. */ FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); /* Parse the structure to the msg structure. */ uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverMsg->pskSelectedIdentity.exLen.data == 0); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_SEND_CERTIFICATE) , HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_SESS_Free(testInfo.clientSession); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC004 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec * @title Trigger the hrr message and select the PSK. * @precon nan * @brief * 1. The PSK is generated during connection establishment, and set on the client. * 2. Set a group so that the server triggers the hrr message, preset the PSK, and establish a connection. * @expect * 1. The setting is successful. * 2. The connection is successfully set up. The server sends the hrr message and selects the PSK. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC004() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); // The PSK is generated during connection establishment, and set on the client. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; // Set a group so that the server triggers the hrr message, preset the PSK, and establish a connection. uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.c_config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.s_config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); HITLS_CFG_SetPskClientCallback(testInfo.c_config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.s_config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO) , HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(testInfo.server->ssl->hsCtx->haveHrr == true); serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverMsg->pskSelectedIdentity.data.data == 0); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(HITLS_Connect(testInfo.client->ssl), HITLS_REC_NORMAL_IO_BUSY); FrameUioUserData *ioUserData2 = BSL_UIO_GetUserData(testInfo.client->io); uint32_t sendLen = ioUserData2->sndMsg.len; ASSERT_TRUE(sendLen != 0); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_SESS_Free(testInfo.clientSession); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC005 * @brief 4.2.11-Pre-Shared Key Extension-94 * @spec * @title Compatibility between session restoration and user-configured PSK * @precon nan * @brief 1. create a tls1.3 connection 2. Configure the user-defined PSK through the callback function. 3. Ensure that the PSK length configured by the user is greater than the PSK length for session restoration. 4. Establish a link again. * @expect 1. The connection is successful. 2. Configuration succeeded. 3. Configuration succeeded. 4. The connection is successful. * @prior Level 2 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMEPSK_AND_SETPSK_FUNC_TC005() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.c_config = HITLS_CFG_NewTLS13Config(); testInfo.s_config = HITLS_CFG_NewTLS13Config(); // The PSK is generated during link establishment. Configure the default 384 algorithm suite on the client. ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; /* Set the 256 cipher suite, preset the PSK, and establish a link. */ uint16_t cipher_suite[] = { HITLS_AES_128_GCM_SHA256, HITLS_AES_256_GCM_SHA384}; HITLS_CFG_SetCipherSuites(testInfo.c_config, cipher_suite, sizeof(cipher_suite)/sizeof(uint16_t)); HITLS_CFG_SetCipherSuites(testInfo.s_config, cipher_suite, sizeof(cipher_suite[0])/sizeof(uint16_t)); ExampleSetPsk("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); HITLS_CFG_SetPskClientCallback(testInfo.c_config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.s_config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_TRUE(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_SERVER_HELLO) , HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverMsg->pskSelectedIdentity.exLen.data != 0); ASSERT_TRUE(serverMsg->pskSelectedIdentity.data.data == 1); ASSERT_TRUE(testInfo.client->ssl != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT) , HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_SESS_Free(testInfo.clientSession); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* During the TLS1.3 HRR handshaking, application messages can not be received*/ /* BEGIN_CASE */ void UT_TLS13_RFC8446_HRR_APP_RECV_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLSConfig(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); /* 1. Initialize the client and server to tls1.3, construct the scenario where the supportedversion values carried by serverhello and hrr are different, */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_SEND_CLIENT_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint32_t sendLenapp = 7; uint8_t sendBufapp[7] = {0x17, 0x03, 0x03, 0x00, 0x02, 0x05, 0x05}; uint32_t writeLen; BSL_UIO_Write(clientTlsCtx->uio, sendBufapp, sendLenapp, &writeLen); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS1_3_RFC8446_Legacy_Version_TC001 * @spec For TLS 1.3, the legacy_record_version set to 0x0403 to client will get alert * @title For TLS 1.3, the legacy_record_version set to 0x0403 to client will get alert * @precon nan * @brief 5.1. Record Layer line 190 * legacy_record_version: MUST be set to 0x0303 for all records generated by a TLS 1.3 implementation other than an initial ClientHello (i.e., one not generated after a HelloRetryRequest), where it MAY also be 0x0301 for compatibility purposes. This field is deprecated and MUST be ignored for all purposes. Previous versions of TLS would use other values in this field under some circumstances. @ */ /* BEGIN_CASE */ void UT_TLS1_3_RFC8446_Legacy_Version_TC001(int statehs) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); /* Configure the server to support only the non-default curve. The server sends the HRR message. */ const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(tlsConfig, groups, groupsSize); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, statehs) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->hsCtx->state == (HITLS_HandshakeState)statehs); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.msg[1] = 0x04u; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_INVALID_PROTOCOL_VERSION); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); if (statehs == TRY_RECV_SERVER_HELLO) { ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); } else { ASSERT_EQ(info.description, ALERT_DECODE_ERROR); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS1_3_RFC8446_Legacy_Version_TC002 * @spec For TLS 1.3, the legacy_record_version set to 0x0403 to server will get alert * @title For TLS 1.3, the legacy_record_version set to 0x0403 to server will get alert * @precon nan * @brief 5.1. Record Layer line 190 * legacy_record_version: MUST be set to 0x0303 for all records generated by a TLS 1.3 implementation other than an initial ClientHello (i.e., one not generated after a HelloRetryRequest), where it MAY also be 0x0301 for compatibility purposes. This field is deprecated and MUST be ignored for all purposes. Previous versions of TLS would use other values in this field under some circumstances. @ */ /* BEGIN_CASE */ void UT_TLS1_3_RFC8446_Legacy_Version_TC002(int statehs) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); /* Configure the server to support only the non-default curve. The server sends the HRR message. */ const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(tlsConfig, groups, groupsSize); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, statehs) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == (HITLS_HandshakeState)statehs); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(server->io); ioClientData->recMsg.msg[1] = 0x04u; ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_INVALID_PROTOCOL_VERSION); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); if (statehs == TRY_RECV_CLIENT_HELLO) { ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); } else { ASSERT_EQ(info.description, ALERT_DECODE_ERROR); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ALERT_PROCESS_TC001 * @spec - * @title During connection establishment, tls13 server receives a warning alert, the connection state change to alerted * @precon nan * @brief 1. Initialize the client and server. Expected result 1. * 2. Initiate a connection, keep the connection status in the receive_client_key_exchange state, and simulate the scenario where the server receives a warning alert message. (Expected result 2) * @expect 1. Complete initialization. * 2. the connection state of server change to alerted * @prior Level 2 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ALERT_PROCESS_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = false; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CERTIFICATE), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint8_t alertMsg[2] = {ALERT_LEVEL_WARNING, ALERT_NO_RENEGOTIATION}; ASSERT_EQ(REC_Write(clientTlsCtx, REC_TYPE_ALERT, alertMsg, sizeof(alertMsg)), HITLS_SUCCESS); // clear the certificate verify in the cache ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(REC_Write(clientTlsCtx, REC_TYPE_ALERT, alertMsg, sizeof(alertMsg)), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_HELLO_REQUEST_TC001 * @spec - * @title Send a hello request when the link status is CM_STATE_IDLE. * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a HelloRequest message and send it to the client. The client invokes the HITLS_Connect interface to receive the message. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the HelloRequest message, the client ignores the message and stays in the TRY_RECV_SERVER_HELLO state after sending the ClientHello message. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_HELLO_REQUEST_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); // Construct a HelloRequest message and send it to the client. uint8_t buf[HS_MSG_HEADER_SIZE] = {0u}; size_t len = HS_MSG_HEADER_SIZE; REC_Write(server->ssl, REC_TYPE_HANDSHAKE, buf, len); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_TRUE(client->ssl != NULL); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(client->ssl->hsCtx->state == TRY_RECV_SERVER_HELLO); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ void SetFrameType(FRAME_Type *frametype, uint16_t versionType, REC_Type recordType, HS_MsgType handshakeType, HITLS_KeyExchAlgo keyExType) { frametype->versionType = versionType; frametype->recordType = recordType; frametype->handshakeType = handshakeType; frametype->keyExType = keyExType; frametype->transportType = BSL_UIO_TCP; } /** @ * @test UT_TLS_TLS13_RFC8446_MODIFIED_SESSID_FROM_SH_TC002 * @spec - * @title Send a empty session id to client. * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a server hello message with empty session id and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the HelloRequest message, the client send a ILLEGAL_PARAMETER alert. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_MODIFIED_SESSID_FROM_SH_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg parsedSH = {0}; uint32_t parseLen = 0; FRAME_Type frameType = {0}; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &parsedSH, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *shMsg = &parsedSH.body.hsMsg.body.serverHello; shMsg->sessionId.size = 0; shMsg->sessionId.state = MISSING_FIELD; shMsg->sessionIdSize.data = 0; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSH, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID); ALERT_Info alert = { 0 }; ALERT_GetInfo(client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: FRAME_CleanMsg(&frameType, &parsedSH); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_MUTI_CCS_TC001 * @spec - * @title IN TLS1.3, mutiple ccs can be received. * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct a ChangeCipherSpec message and send it to the client five times. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. return HITLS_REC_NORMAL_RECV_BUF_EMPTY. * @prior Level 1 * @auto TRUE @ */ /* IN TLS1.3, mutiple ccs can be received*/ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_MUTI_CCS_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint32_t sendLenccs = 6; uint8_t sendBufccs[6] = {0x14, 0x03, 0x03, 0x00, 0x01, 0x01}; uint32_t writeLen; for (int i = 0; i < 5; i++) { BSL_UIO_Write(serverTlsCtx->uio, sendBufccs, sendLenccs, &writeLen); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); } ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static int32_t SendCcs(HITLS_Ctx *ctx, uint8_t *data, uint8_t len) { /** Write records. */ int32_t ret = REC_Write(ctx, REC_TYPE_CHANGE_CIPHER_SPEC, data, len); if (ret != HITLS_SUCCESS) { return ret; } /* If isFlightTransmitEnable is enabled, the stored handshake information needs to be sent. */ uint8_t isFlightTransmitEnable; (void)HITLS_GetFlightTransmitSwitch(ctx, &isFlightTransmitEnable); if (isFlightTransmitEnable == 1) { 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) { return HITLS_REC_ERR_IO_EXCEPTION; } } return HITLS_SUCCESS; } static int32_t SendAlert(HITLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { uint8_t data[ALERT_BODY_LEN]; /** Obtain the alert level. */ data[0] = level; data[1] = description; /** Write records. */ int32_t ret = REC_Write(ctx, REC_TYPE_ALERT, data, ALERT_BODY_LEN); if (ret != HITLS_SUCCESS) { return ret; } /* If isFlightTransmitEnable is enabled, the stored handshake information needs to be sent. */ uint8_t isFlightTransmitEnable; (void)HITLS_GetFlightTransmitSwitch(ctx, &isFlightTransmitEnable); if (isFlightTransmitEnable == 1) { 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) { return HITLS_REC_ERR_IO_EXCEPTION; } } return HITLS_SUCCESS; } /** @ * @test UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_RECEIVES_ENCRYPTED_CCS_TC001 * @spec - * @title The encrypted CCS is received when the plaintext CCS is received. * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct encrypted CCS and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the CCS message, the client send a UNEXPECTED_MESSAGE alert. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_RECEIVES_ENCRYPTED_CCS_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); // Sends serverhello to the peer end. ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); // Processing serverhello ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); serverTlsCtx->recCtx->outBuf->end = 0; uint32_t hashLen = SAL_CRYPT_DigestSize(serverTlsCtx->negotiatedInfo.cipherSuiteInfo.hashAlg); ASSERT_EQ(HS_SwitchTrafficKey(serverTlsCtx, serverTlsCtx->hsCtx->serverHsTrafficSecret, hashLen, true), HITLS_SUCCESS); uint8_t data = 1; // send crypto ccs ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->sndMsg.msg[0] = REC_TYPE_APP; FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); // process crypto ccs ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ #define ALERT_UNKNOWN_DESCRIPTION 254 /** @ * @test UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_UNKNOWN_DESCRIPTION_TC001 * @spec - * @title RFC8446 6.2 All alerts defined below in this section, as well as all unknown alerts, are universally considered fatal as of TLS 1.3 (see Section 6). * @precon nan * @brief 1. Use the configuration items to configure the client and server. Expected result 1 is obtained. * 2. Construct alert message with alert level warning and ALERT_UNKNOWN_DESCRIPTION, and send it to the server. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. After receiving the alert message, the server send a FATAL alert. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_UNKNOWN_DESCRIPTION_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportClientVerify = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_FINISH) == HITLS_SUCCESS); ASSERT_TRUE(SendAlert(client->ssl, ALERT_LEVEL_WARNING, ALERT_UNKNOWN_DESCRIPTION) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); HITLS_Ctx *Ctx = FRAME_GetTlsCtx(server); ALERT_Info alert = { 0 }; ALERT_GetInfo(Ctx, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_UNKNOWN_DESCRIPTION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test SDV_TLS13_RFC8446_REQUEST_CLIENT_HELLO_TC008 * @brief 2.1. Incorrect DHE Share * @spec If the client has not provided a sufficient "key_share" extension (e.g., it includes only DHE or ECDHE groups unacceptable to or unsupported by the server), the server corrects the mismatch with a HelloRetryRequest and the client needs to restart the handshake with an appropriate "key_share" extension, as shown in Figure 2. If no common cryptographic parameters can be negotiated, the server MUST abort the handshake with an appropriate alert. * @title Configure groups_list:"brainpoolP512r1:X25519" on the client and groups_list:"brainpoolP512r1:X25519" on the server. Observe the link setup result and check whether the server sends Hello_Retry_Requset. * @precon nan * @brief 1. Configure groups_list:"brainpoolP512r1:X25519" on the client and groups_list:"brainpoolP512r1:X25519" on the server. * @expect 1. Send clienthello with X25519 keyshare. The link is established successfully. 2. The server does not send Hello_Retry_Requset. * @prior Level 2 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_REQUEST_CLIENT_HELLO_TC001() { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *clientconfig = NULL; HITLS_Config *serverconfig = NULL; clientconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(clientconfig != NULL); serverconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(serverconfig != NULL); uint16_t clientgroups[] = {HITLS_EC_GROUP_BRAINPOOLP512R1, HITLS_EC_GROUP_CURVE25519}; uint16_t servergroups[] = {HITLS_EC_GROUP_BRAINPOOLP512R1, HITLS_EC_GROUP_CURVE25519}; ASSERT_EQ(HITLS_CFG_SetGroups(serverconfig, servergroups, sizeof(servergroups)/sizeof(uint16_t)) , HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetGroups(clientconfig, clientgroups, sizeof(clientgroups)/sizeof(uint16_t)) , HITLS_SUCCESS); client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recBuf = ioUserData->recMsg.msg; uint32_t recLen = ioUserData->recMsg.len; ASSERT_TRUE(recLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = SERVER_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recBuf, recLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverHello = &frameMsg.body.hsMsg.body.serverHello; ASSERT_TRUE(serverHello->keyShare.data.group.data == HITLS_EC_GROUP_CURVE25519); ASSERT_EQ(server->ssl->hsCtx->haveHrr, false); // Continue to establish the link. ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(clientconfig); HITLS_CFG_FreeConfig(serverconfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_Legacy_Version_TC001 * @spec For TLS 1.3, the legacy_record_version set to 0x0403 to server will get alert * @title For TLS 1.3, the legacy_record_version set to 0x0403 to server will get alert * @precon nan * @brief 5.1. Record Layer line 190 * legacy_record_version: MUST be set to 0x0303 for all records generated by a TLS 1.3 implementation other than an initial ClientHello (i.e., one not generated after a HelloRetryRequest), where it MAY also be 0x0301 for compatibility purposes. This field is deprecated and MUST be ignored for all purposes. Previous versions of TLS would use other values in this field under some circumstances. @ */ /* BEGIN_CASE */ void UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_Legacy_Version_TC001(int statehs) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); /* Configure the server to support only the non-default curve. The server sends the HRR message. */ const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(tlsConfig, groups, groupsSize); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, statehs) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == (HITLS_HandshakeState)statehs); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(server->io); ioClientData->recMsg.msg[1] = 0x04u; ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_INVALID_PROTOCOL_VERSION); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); if (statehs == TRY_RECV_CLIENT_HELLO) { ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); } else { ASSERT_EQ(info.description, ALERT_DECODE_ERROR); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_MIDDLE_BOX_COMPAT_TC001 * @spec - * @title Test TLS 1.3 connection and data transfer when middlebox compatibility mode is enabled or disabled * @precon nan * @brief 1. Initialize the client and server using the default configuration. Expected result 1. * 2. Set the middlebox compatibility mode for both the client and server based on the isMiddleBoxCompat parameter. Expected result 2. * 3. Stop the server state at TRY_RECV_CLIENT_HELLO and determine the length of the session ID at this time. Expected result 3. * 4. The server calls the HITLS_Accept function and then determines the next state of the server. Expected result 4. * 5. Continue to establish a connection. Expected result 5. * @expect 1 Initialization succeeded. * 2. Successful setup. * 3. If isMiddleBoxCompat is true, then the session ID length is 32, otherwise it is 0 * 4. If isMiddleBoxCompat is true, the next state of the server is TRY_SEND_CHANGE_CIPHER_SPEC, otherwise it is TRY_SEND_ENCRYPTED_EXTENSIONS. * 5. The connection between the client and server is successfully established. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_SDV_TLS1_3_RFC8446_CONSISTENCY_MIDDLE_BOX_COMPAT_TC001(int isMiddleBoxCompat) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_CFG_SetMiddleBoxCompat(tlsConfig, isMiddleBoxCompat); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); uint32_t parseLen = 0; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; if (isMiddleBoxCompat) { ASSERT_TRUE(clientMsg->sessionIdSize.data == TLS_HS_MAX_SESSION_ID_SIZE); ASSERT_TRUE(clientMsg->sessionId.data != NULL); (void)HITLS_Accept(server->ssl); ASSERT_EQ(server->ssl->hsCtx->state, TRY_SEND_CHANGE_CIPHER_SPEC); } else { ASSERT_TRUE(clientMsg->sessionIdSize.data == 0); ASSERT_TRUE(clientMsg->sessionId.data == NULL); (void)HITLS_Accept(server->ssl); ASSERT_EQ(server->ssl->hsCtx->state, TRY_SEND_ENCRYPTED_EXTENSIONS); } ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_2.c
C
unknown
145,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. */ /* BEGIN_HEADER */ #include "rec_wrapper.h" #include "alert.h" #include "hitls_crypt_init.h" #include "common_func.h" #include "securec.h" #include "hitls_error.h" #include "hs.h" #include "stub_replace.h" #include "frame_tls.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "frame_link.h" #include "hlt.h" #define UT_TIMEOUT 3 /* END_HEADER */ typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; } HsTestInfo; int32_t NewConfig(HsTestInfo *testInfo) { switch (testInfo->version) { case HITLS_VERSION_DTLS12: testInfo->config = HITLS_CFG_NewDTLS12Config(); break; case HITLS_VERSION_TLS13: testInfo->config = HITLS_CFG_NewTLS13Config(); break; case HITLS_VERSION_TLS12: testInfo->config = HITLS_CFG_NewTLS12Config(); break; default: break; } if (testInfo->config == NULL || testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetClientVerifySupport(testInfo->config, true); HITLS_CFG_SetExtenedMasterSecretSupport(testInfo->config, true); HITLS_CFG_SetNoClientCertSupport(testInfo->config, true); HITLS_CFG_SetRenegotiationSupport(testInfo->config, true); HITLS_CFG_SetPskServerCallback(testInfo->config, (HITLS_PskServerCb)ExampleServerCb); return HITLS_SUCCESS; } static int32_t DoHandshake(HsTestInfo *testInfo) { /* Construct a connection. */ testInfo->client = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } return FRAME_CreateConnection(testInfo->client, testInfo->server, true, HS_STATE_BUTT); } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_OBSOLETE_RESERVED_FUNC_TC001 * @spec - * @title Expired signature algorithm * @precon nan * @brief 1. Initialize the client server to tls1.3 and construct the scenario where the client uses all the obsolete_RESERVED signature algorithms in polling mode, Expected result: The connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_OBSOLETE_RESERVED_FUNC_TC001(int signAlg) { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); HITLS_CFG_SetSignature(testInfo.config, (uint16_t *)&signAlg, 1); ASSERT_EQ(DoHandshake(&testInfo), HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_OBSOLETE_RESERVED_FUNC_TC002 * @spec - tls1.3 Expired group algorithm OBSOLETE_RESERVED test * @title * @precon nan * @brief 1. Initialize the client and server to tls1.3 and construct the scenario where the client uses all the obsolete_RESERVED group algorithms in polling mode, Expected result: The connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_OBSOLETE_RESERVED_FUNC_TC002(int group) { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); HITLS_CFG_SetGroups(testInfo.config, (uint16_t *)&group, 1); ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_ServerHelloNoSupportedVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.supportedVersion.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC001 * @spec - * @title server hello really necessary extensions * @precon nan * @brief 1. If the server sends a HelloRetryRequest message without supported_versions, the connection fails to be established and the client generates an alarm. Expected result: The connection fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC001() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = { TRY_SEND_HELLO_RETRY_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerHelloNoSupportedVersion }; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC002 * @spec - * @title server hello really necessary extension * @precon nan * @brief 1. In certificate authentication, the first connection is established. If the ServerHello message sent by the Server does not contain the signature_algorithms field, the connection fails to be established and the client generates an alarm. Expected result: The connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC002() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerHelloNoSupportedVersion }; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_ResumeServerHelloNoSupportedVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { if (ctx->session == NULL) { return; } (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.supportedVersion.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_ResumeClientHelloNoSupportedVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { if (ctx->session == NULL) { return; } (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.supportedVersion.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_ClientHelloNoSupportedVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.supportedVersion.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC003 * @spec - * @title server Hello message extension is missing. * @precon nan * @brief Certificate authentication, session recovery, the Server sends the ServerHello message without the signature_algorithms, the session recovery fails, and the client generates an alarm. * Expected result: connect establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC003() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ResumeServerHelloNoSupportedVersion }; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); ClearWrapper(); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC004 * @spec - * @title client hello is missing the necessary extension. * @precon nan * @brief 1. In certificate authentication, the first connection is established. If the clientHello message sent by the * client does not contain signature_algorithms, the connection fails to be established and the server * generates an alarm. Expected result: The connection fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC004() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHelloNoSupportedVersion }; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC005 * @spec - * @title client Hello packet extension is missing. * @precon nan * @brief Certificate authentication, session recovery. If the client sends a clientHello message without * signature_algorithms, the session recovery fails and the server generates an alarm. *Expected result: The * connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC005() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); HITLS_CFG_SetSessionTimeout(testInfo.config, UT_TIMEOUT); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ResumeClientHelloNoSupportedVersion}; RegisterWrapper(wrapper); /* First handshake */ ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); ClearWrapper(); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_ClientHello2NoSupportedVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { if (!ctx->hsCtx->haveHrr) { return; } (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.supportedVersion.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC006 * @spec - * @title client hello is missing the necessary extension. * @precon nan * @brief 1. After receiving the HelloRetryRequest message, the client sends the second ClientHello message. If the * client does not have the signature_algorithms message, the connection fails to be established and the server * generates an alarm. Expected result: The connection fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC006() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHello2NoSupportedVersion }; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_Client2HelloNoSupportedGroup(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { if (!ctx->hsCtx->haveHrr) { return; } (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.supportedGroups.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_ClientHelloNoSupportedGroup(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.supportedGroups.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC007 * @spec - * @title client hello is missing the necessary extension. * @precon nan * @brief 1. During DHE key exchange, if the ClientHello does not contain "supported_groups", the connection fails to be established and the server generates an alarm. Expected result: The connection fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC007() { FRAME_Init(); HsTestInfo testInfo = { 0 }; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHelloNoSupportedGroup }; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_MISSING_EXTENSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC008 * @spec - * @title client hello really necessary extension * @precon nan * @brief 1. After the client receives the HelloRetryRequest message, the client sends the second ClientHello message without the supported_groups field. In this case, the connection fails to be established and the server generates an alarm. Expected result: The connection fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NECESSARY_EXTENSION_FUNC_TC008() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client2HelloNoSupportedGroup }; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_MISSING_EXTENSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_appendix.c
C
unknown
24,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. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "bsl_sal.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "securec.h" #include "rec_wrapper.h" #include "conn_init.h" #include "rec.h" #include "parse.h" #include "hs_msg.h" #include "alert.h" #include "hitls_crypt_init.h" #include "common_func.h" /* END_HEADER */ #define g_uiPort 2987 typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; } HsTestInfo; int32_t NewConfig(HsTestInfo *testInfo) { /* Construct the configuration.*/ switch (testInfo->version) { case HITLS_VERSION_DTLS12: testInfo->config = HITLS_CFG_NewDTLS12Config(); break; case HITLS_VERSION_TLS13: testInfo->config = HITLS_CFG_NewTLS13Config(); break; case HITLS_VERSION_TLS12: testInfo->config = HITLS_CFG_NewTLS12Config(); break; default: break; } if (testInfo->config == NULL || testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetClientVerifySupport(testInfo->config, true); HITLS_CFG_SetExtenedMasterSecretSupport(testInfo->config, true); HITLS_CFG_SetNoClientCertSupport(testInfo->config, true); HITLS_CFG_SetRenegotiationSupport(testInfo->config, true); HITLS_CFG_SetPskServerCallback(testInfo->config, (HITLS_PskServerCb)ExampleServerCb); return HITLS_SUCCESS; } static int32_t DoHandshake(HsTestInfo *testInfo) { HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); testInfo->client = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } return FRAME_CreateConnection(testInfo->client, testInfo->server, true, HS_STATE_BUTT); } static void Test_Cert_len0(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); FRAME_CertificateMsg *certifiMsg = &frameMsg.body.hsMsg.body.certificate; certifiMsg->certsLen.state = ASSIGNED_FIELD; certifiMsg->certsLen.data = 0; certifiMsg->certificateReqCtxSize.state = ASSIGNED_FIELD; certifiMsg->certificateReqCtxSize.data = 0; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_CertPackAndParse(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); if (frameMsg.body.hsMsg.body.certificate.certificateReqCtx.data == NULL) { frameMsg.body.hsMsg.body.certificate.certificateReqCtxSize.data = 1; frameMsg.body.hsMsg.body.certificate.certificateReqCtxSize.state = INITIAL_FIELD; uint8_t *cerReqData = BSL_SAL_Calloc(1, 1); frameMsg.body.hsMsg.body.certificate.certificateReqCtx.data = cerReqData; frameMsg.body.hsMsg.body.certificate.certificateReqCtx.size = 1; frameMsg.body.hsMsg.body.certificate.certificateReqCtx.state = INITIAL_FIELD; } memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC003 * @spec - * @titleThe client receives a Certificate message with zero length. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. The client initiates a TLS over TCP connection request. When the client receives the request from the server, the client receives the request from the server. After receiving the Hello message, the server constructs a Certificate message with zero length and sends the message to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message with the level of ALERT_ LEVEL_FATAL and description of * ALERT_DECODE_ERROR. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC003(void) { FRAME_Init(); HsTestInfo testInfo = {0}; /* 1. Use the default configuration items to configure the client and server. */ testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); testInfo.config->isSupportNoClientCert = false; testInfo.config->isSupportClientVerify = true; /* 2. The client initiates a TLS over TCP connection request. When the client receives the request from the server, * the client receives the request from the server. After receiving the Hello message, the server constructs a * Certificate message with zero length and sends the message to the client. */ RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, &wrapper, Test_Cert_len0}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_EE_len0(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, ENCRYPTED_EXTENSIONS); memset_s(data, bufSize, 0, bufSize); if (ctx->isClient) { data[0] = ENCRYPTED_EXTENSIONS; data[1] = 0X00; data[2] = 0X00; data[3] = 0X00; } EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC004 * @spec - * @title The client receives an EE message with zero length. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. The client initiates a TLS over TCP connection request. After receiving the client Hello message, the * client constructs a certificate with zero length. Send the request message to the client. Expected result 2 * is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message with the level of ALERT_ LEVEL_FATAL and description ALERT_DECODE_ERROR. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC004(void) { FRAME_Init(); HsTestInfo testInfo = {0}; /* 1. Use the default configuration items to configure the client and server. */ testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); testInfo.config->isSupportNoClientCert = false; testInfo.config->isSupportClientVerify = true; /* 2. The client initiates a TLS over TCP connection request. After receiving the CH message, the client * constructs a EE with zero length. Send the request message to the client. */ RecWrapper wrapper = {TRY_RECV_ENCRYPTED_EXTENSIONS, REC_TYPE_HANDSHAKE, true, &wrapper, Test_EE_len0}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC008 * @title The client receives an key update message with zero length. * @brief The client receives an key update message with zero length. Expect result 1 * @expect 1. The client sends an ALERT message with the level of ALERT_ LEVEL_FATAL and description ALERT_DECODE_ERROR. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC008(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; uint8_t keyUpdateMsg[] = {KEY_UPDATE, 0, 0, 0}; ASSERT_TRUE(REC_Write(serverTlsCtx, REC_TYPE_HANDSHAKE, keyUpdateMsg, sizeof(keyUpdateMsg)) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen) == HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = {0}; ALERT_GetInfo(clientTlsCtx, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_Cert_verify_len0(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_VERIFY); FRAME_CertificateVerifyMsg *CertveriMsg = &frameMsg.body.hsMsg.body.certificateVerify; CertveriMsg->signSize.data = 0; CertveriMsg->signSize.state = ASSIGNED_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC005 * @spec - * @titleThe client receives a Certificate verify message whose length is zero. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. The client initiates a TLS over TCP connection request. After receiving the client Hello message, the * client constructs a certificate with zero length. Send the verify message to the client. Expected result * 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message with the level of ALERT_ LEVEL_FATAL and description ALERT_DECODE_ERROR. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC005(void) { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); testInfo.config->isSupportNoClientCert = false; testInfo.config->isSupportClientVerify = true; RecWrapper wrapper = {TRY_SEND_CERTIFICATE_VERIFY, REC_TYPE_HANDSHAKE, false, &wrapper, Test_Cert_verify_len0}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_finished_len0(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, FINISHED); FRAME_FinishedMsg *FinishedMsg = &frameMsg.body.hsMsg.body.finished; FinishedMsg->verifyData.size = 0; FinishedMsg->verifyData.state = ASSIGNED_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC006 * @spec - * @titleThe client receives a finished message with zero length. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. The client initiates a TLS over TCP connection request and receives the request from the client. After the Hello message is sent, construct a finished message with zero length and send the message to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends an ALERT message. The level is ALERT_Level_FATAL and the description is ALERT_DECODE_ERROR. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC006(void) { FRAME_Init(); HsTestInfo testInfo = {0}; /* 1. Use the default configuration items to configure the client and server. */ testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); testInfo.config->isSupportNoClientCert = false; testInfo.config->isSupportClientVerify = true; /* 2. The client initiates a TLS over TCP connection request and receives the request from the client. * After the Hello message is sent, construct a finished message with zero length and send the message to the * client. */ RecWrapper wrapper = {TRY_SEND_FINISH, REC_TYPE_HANDSHAKE, false, &wrapper, Test_finished_len0}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_NewSessionTicket_len0(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, NEW_SESSION_TICKET); FRAME_NewSessionTicketMsg *newsessionTMsg = &frameMsg.body.hsMsg.body.newSessionTicket; newsessionTMsg->ticketSize.data = 0; newsessionTMsg->ticketSize.state = ASSIGNED_FIELD; ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC007 * @spec - * @titleThe client receives a NewSessionTicket message with zero length. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. Expected result 1 is obtained. * 2. The client initiates a TLS over TCP connection request and receives the request from the client. After receiving the Hello message, construct a New SessionTicket message with zero length and send it to the client. Expected result 2 is obtained. * @expect 1. The initialization is successful. * 2. The client sends the ALERT message. The level is ALERT_ LEVEL_FATAL and the description is ALERT_DECODE_ERROR. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECV_ZEROLENGTH_MSG_FUNC_TC007(void) { FRAME_Init(); HsTestInfo testInfo = {0}; /* 1. Use the default configuration items to configure the client and server. */ testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); testInfo.config->isSupportNoClientCert = false; testInfo.config->isSupportClientVerify = true; /* 2. The client initiates a TLS over TCP connection request and receives the request from the client. * After receiving the Hello message, construct a New SessionTicket message with zero length and send it to * the client. */ RecWrapper wrapper = {TRY_SEND_NEW_SESSION_TICKET, REC_TYPE_HANDSHAKE, false, &wrapper, Test_NewSessionTicket_len0}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTMSG_FUNC_TC001 * @spec - * @title Abnormal CertMsg packet * @precon nan * @brief 1. Enable the dual-end verification. Change the value of certificate_request_context in the certificate message sent by the client to a value other than 0. Expected result 1 is obtained. Result 1: The server sends an alert message and disconnects the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTMSG_FUNC_TC001() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_CertPackAndParse}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_CertReqAbCtxLen(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); if (frameMsg.body.hsMsg.body.certificateReq.certificateReqCtx.data == NULL) { ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_REQUEST); frameMsg.body.hsMsg.body.certificateReq.certificateReqCtxSize.data = 1; frameMsg.body.hsMsg.body.certificateReq.certificateReqCtxSize.state = INITIAL_FIELD; uint8_t *cerReqData = BSL_SAL_Calloc(1, 1); frameMsg.body.hsMsg.body.certificateReq.certificateReqCtx.data = cerReqData; frameMsg.body.hsMsg.body.certificateReq.certificateReqCtx.size = 1; frameMsg.body.hsMsg.body.certificateReq.certificateReqCtx.state = INITIAL_FIELD; } memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC001 * @spec - * @title Abnormal CertReqMsg message * @precon nan * @brief 1. Enable the dual-end check. Change the value of certificate_request_context in the certificate_request * message sent by the server to a value other than 0. Expected result 1 is obtained. Result 1: The server * sends an alert message and disconnects the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC001() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_CertReqAbCtxLen}; RegisterWrapper(wrapper); /* Handshake */ ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_NO_CERT_FUNC_TC001 * @spec A Finished message MUST be sent regardless of whether the Certificate message is empty. * @title During the normal handshake, the peer certificate can be empty, the certificate message sent by the client is * empty, and the certificate message sent by the server is not empty. The handshake is successful. The finished * message is sent after the certificate message and the content is correct. * @precon nan * @brief 4.4.2. Certificate row114 1. Enable the dual-end verification, allow the peer certificate to be empty, set the client certificate to be empty, and establish a connection. * @expect 1. The connection is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_NO_CERT_FUNC_TC001(int isSupportNoClientCert) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", 0, 0, 0, 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = (bool)isSupportNoClientCert; if (config->isSupportNoClientCert) { client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); } else { client = FRAME_CreateLink(config, BSL_UIO_TCP); } ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC002 * @spec 1. If the client does not set the root certificate but the server sets the complete certificate chain, the client fails to construct the certificate chain, and the handshake fails and the unsupported_certificate alarm is reported. By default, the preceding alarm is generated. In the current code, the alarm is generated as bad_certificate. * @brief If the client cannot construct an acceptable chain using the provided * certificates and decides to abort the handshake, then it MUST abort the * handshake with an appropriate certificate-related alert * (by default, "unsupported_certificate"; see Section 6.2 for more information). * 4.4.2 Certificate row 136 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { 0, "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC003 * @spec 1. The root certificate is configured on the client. Incomplete certificate chain is configured on both the client and server. If the server fails to construct the certificate chain, the handshake fails and the unsupported_certificate alarm is reported. By default, the alarm is the preceding alarm. In the current code, the alarm is the bad_certificate alarm. * @brief If the client cannot construct an acceptable chain using the provided * certificates and decides to abort the handshake, then it MUST abort the * handshake with an appropriate certificate-related alert * (by default, "unsupported_certificate"; see Section 6.2 for more information). * 4.4.2 Certificate row 136 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "ecdsa/ca-nist521.der", 0, "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC004 * @spec 1. If the client sets an incorrect root certificate and the server sets a complete certificate chain, the client fails to construct the certificate chain, and the handshake fails and the unsupported_certificate alarm is reported. By default, the preceding alarm is generated. In the current code, the alarm is generated as bad_certificate. * @brief If the client cannot construct an acceptable chain using the provided * certificates and decides to abort the handshake, then it MUST abort the * handshake with an appropriate certificate-related alert * (by default, "unsupported_certificate"; see Section 6.2 for more information). * 4.4.2 Certificate row 136 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC004(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "rsa_sha/ca-3072.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC005 * @spec 1. If the client does not match a proper algorithm and fails to construct a certificate chain, the handshake fails and the unsupported_certificate alarm is reported. By default, the preceding alarm is generated. In the current code, the HANDSHAKE_FAILURE alarm is generated. * @brief If the client cannot construct an acceptable chain using the provided * certificates and decides to abort the handshake, then it MUST abort the * handshake with an appropriate certificate-related alert * (by default, "unsupported_certificate"; see Section 6.2 for more information). * 4.4.2 Certificate row 136 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTCHAIN_FUNC_TC005(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t serverSignAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; uint16_t clientSignAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_CFG_SetSignature(&client->ssl->config.tlsConfig, clientSignAlgs, sizeof(clientSignAlgs) / sizeof(uint16_t)); HITLS_CFG_SetSignature(&server->ssl->config.tlsConfig, serverSignAlgs, sizeof(serverSignAlgs) / sizeof(uint16_t)); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_ERR_NO_SERVER_CERTIFICATE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *sndBuf = ioUserData->sndMsg.msg; uint32_t sndLen = ioUserData->sndMsg.len; ASSERT_TRUE(sndLen != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {0}; FRAME_Type frameType = {0}; frameType.recordType = REC_TYPE_ALERT; ASSERT_TRUE(FRAME_ParseMsg(&frameType, sndBuf, sndLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_HANDSHAKE_FAILURE); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_CertReqPackAndParseNoEx(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_REQUEST); frameMsg.body.hsMsg.body.certificateReq.signatureAlgorithmsSize.data = 0; frameMsg.body.hsMsg.body.certificateReq.signatureAlgorithmsSize.state = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC002 * @spec - * @title Abnormal CertReqMsg packet * @precon nan * @brief 1. Enable the dual-end verification. Change the value of certificate_request_context in the certificate_request message sent by the server to a value other than 0. Expected result 1 is obtained. Result 1: The server sends an alert message and disconnects the connection. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC002() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_CertReqPackAndParseNoEx}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_PARSE_INVALID_MSG_LEN); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_CertReqPackAndParseNoSign(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; // The eighth digit indicates the type of the first extension. Change the type of the first extension to key share. *(uint16_t *)(data + 8) = HS_EX_TYPE_KEY_SHARE; FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC003 * @spec - * @title Abnormal CertReqMsg packet * @precon nan * @brief 1. Enable the dual-end verification, set the extension field in the server certificate request to exclude the signature algorithm, and establish a connection. Expected result: The connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC003() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = { TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_CertReqPackAndParseNoSign}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_CertReqPackAndParseUnknownEx(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_REQUEST); frameMsg.body.hsMsg.body.certificateReq.signatureAlgorithms.state = DUPLICATE_FIELD; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); *(uint16_t *)(data + 8) = HS_EX_TYPE_KEY_SHARE; EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC004 * @spec - * @title Abnormal CertReqMsg packet * @precon nan * @brief 1. Enable the dual-end verification, set the extension field in the server certificate request to exclude * the signature algorithm, and establish a connection. Expected result: The connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC004() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = { TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_CertReqPackAndParseUnknownEx}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC005 * @spec - * @title Abnormal CertReqMsg packet * @precon nan * @brief 1. Initialize the client and server to tls1.3, and construct the scenario where the client and server sends an alert message after receiving the hrr message and serverhello message, Expected Alert Message Encryption @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC005() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = {TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_CertReqAbCtxLen}; RegisterWrapper(wrapper); ASSERT_EQ( FRAME_CreateConnection(testInfo.client, testInfo.server, true, TRY_RECV_CERTIFICATE_REQUEST), HITLS_SUCCESS); HITLS_Connect(testInfo.client->ssl); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.client->io); uint8_t *buffer = ioUserData->sndMsg.msg; uint32_t len = ioUserData->sndMsg.len; ASSERT_TRUE(len != 0); uint32_t parseLen = 0; FRAME_Msg frameMsg = {}; ASSERT_TRUE(ParserTotalRecord(testInfo.client, &frameMsg, buffer, len, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.type, REC_TYPE_ALERT); ASSERT_EQ(frameMsg.body.alertMsg.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_EmptyCertMsg(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); FrameCertItem *certItem = frameMsg.body.hsMsg.body.certificate.certItem; frameMsg.body.hsMsg.body.certificate.certItem = NULL; while (certItem != NULL) { FrameCertItem *temp = certItem->next; BSL_SAL_FREE(certItem->cert.data); BSL_SAL_FREE(certItem->extension.data); BSL_SAL_FREE(certItem); certItem = temp; } memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTMSG_FUNC_TC002 * @spec - * @title Abnormal CertReqMsg packet * @precon nan * @brief 1. Enable the dual-end verification. If the certificate message does not contain the certificate, the connection is established. Expected result: A decode error is returned when the connection fails to be established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTMSG_FUNC_TC002() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_EmptyCertMsg}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTMSG_FUNC_TC003 * @spec - * @title Abnormal CertReqMsg packet * @precon nan * @brief 1. Enable the single-end authentication. If the certificate message does not contain the certificate, establish a connection. Expected result: Decode error is returned when the connection fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTMSG_FUNC_TC003() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetClientVerifySupport(testInfo.config, false), HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_EmptyCertMsg}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_CertReqPackAndParse(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_REQUEST); memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC000 * @spec - * @title Verify the parsing and packaging functions of the cerreqmsg test framework. * @precon nan * @brief 1. Enable the dual-end check. Change the value of certificate_request_context in the certificate_request message sent by the server to a value other than 0. Expected result 1 is obtained. Result 1: The server sends an alert message and disconnects the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ABNORMAL_CERTREQMSG_FUNC_TC000() { FRAME_Init(); HsTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; ASSERT_EQ(NewConfig(&testInfo), HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_CertReqPackAndParse}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SIGN_ERR_FUNC_TC001 * @spec * 1. Set the client server to tls1.3 and the client signature algorithm to ecdsa-sha1. The expected connection * establishment fails. * @brief If the server cannot produce a certificate chain that is signed only via the indicated * supported algorithms, then it SHOULD continue the handshake by sending the client a certificate * chain of its choice that may include algorithms that are not known to be supported by the client. * This fallback chain SHOULD NOT use the deprecated SHA-1 hash algorithm in general, but MAY do so * if the client' s advertisement permits it, and MUST NOT do so otherwise. * 4.4.2.2. Server Certificate Selection row 135 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SIGN_ERR_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo serverCertInfo = { "ecdsa_sha1/ca-nist521.der", "ecdsa_sha1/inter-nist521.der", "ecdsa_sha1/end384-sha1.der", 0, "ecdsa_sha1/end384-sha1.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SHA1}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &serverCertInfo); ASSERT_TRUE(server != NULL); client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &serverCertInfo); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH); ALERT_Info alert = {0}; ALERT_GetInfo(client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_INTERNAL_ERROR); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static int32_t GetDisorderServerEEMsg(FRAME_LinkObj *server, uint8_t *data, uint32_t len, uint32_t *usedLen) { uint32_t readLen = 0; uint32_t offset = 0; uint8_t tmpData[TEMP_DATA_LEN] = {0}; uint32_t tmpLen = sizeof(tmpData); (void)HITLS_Accept(server->ssl); int32_t ret = FRAME_TransportSendMsg(server->io, tmpData, tmpLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } tmpLen = readLen; uint8_t serverHelloData[TEMP_DATA_LEN] = {0}; uint32_t serverHelloLen = sizeof(serverHelloData); (void)HITLS_Accept(server->ssl); ret = FRAME_TransportSendMsg(server->io, serverHelloData, serverHelloLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } serverHelloLen = readLen; (void)HITLS_Accept(server->ssl); ret = FRAME_TransportSendMsg(server->io, &data[offset], len - offset, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } offset += readLen; if (memcpy_s(&data[offset], len - offset, serverHelloData, serverHelloLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += serverHelloLen; *usedLen = offset; return HITLS_SUCCESS; } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECTMSG_FUNC_TC001 * @spec 1. During the handshake, the server sends an EncryptedExtensions message before the ServerHello message. Expected result: The client returns an alert. The level is ALERT_Level_FATAL, description is ALERT_UNEXPECTED_MESSAGE, and the handshake is interrupted. * @brief In all handshakes, the server MUST send the EncryptedExtensions message immediately after the ServerHello message. * 4.3.1. Encrypted Extensions row 105 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECTMSG_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_HANDSHAKING); ASSERT_EQ(client->ssl->hsCtx->state, TRY_RECV_SERVER_HELLO); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderServerEEMsg(server, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(client->io, data, len) == HITLS_SUCCESS); ASSERT_TRUE(ioUserData->recMsg.len != 0); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info alert = {0}; ALERT_GetInfo(client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static int32_t GetDisorderServerCertMsg(FRAME_LinkObj *server, uint8_t *data, uint32_t len, uint32_t *usedLen) { uint32_t readLen = 0; uint32_t offset = 0; uint8_t tmpData[TEMP_DATA_LEN] = {0}; uint32_t tmpLen = sizeof(tmpData); (void) HITLS_Accept(server->ssl); int32_t ret = FRAME_TransportSendMsg(server->io, tmpData, tmpLen, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } tmpLen = readLen; (void) HITLS_Accept(server->ssl); ret = FRAME_TransportSendMsg(server->io, &data[offset], len - offset, &readLen); if (readLen == 0 || ret != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } offset += readLen; if (memcpy_s(&data[offset], len - offset, tmpData, tmpLen) != EOK) { return HITLS_MEMCPY_FAIL; } offset += tmpLen; *usedLen = offset; return HITLS_SUCCESS; } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECTMSG_FUNC_TC002 * @spec 1. The handshake uses certificate authentication. During the handshake, the server sends a Certificate Request message before sending the EncryptedExtensions extension. Expected result: The client returns an alert, whose level is ALERT_LEVEL_FATAL, description is ALERT_UNEXPECTED_MESSAGE, and the handshake is interrupted. * @brief A server which is authenticating with a certificate MAY optionally request * a certificate from the client. This message, if sent, MUST follow EncryptedExtensions. * 4.3.2. Certificate Request row 107 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNEXPECTMSG_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = {0}; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); config->isSupportClientVerify = true; client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_ENCRYPTED_EXTENSIONS), HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_HANDSHAKING); ASSERT_EQ(client->ssl->hsCtx->state, TRY_RECV_ENCRYPTED_EXTENSIONS); uint8_t data[MAX_RECORD_LENTH] = {0}; uint32_t len = MAX_RECORD_LENTH; ASSERT_TRUE(GetDisorderServerCertMsg(server, data, len, &len) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ASSERT_TRUE(ioUserData->recMsg.len == 0); ASSERT_TRUE(FRAME_TransportRecMsg(client->io, data, len) == HITLS_SUCCESS); ASSERT_TRUE(ioUserData->recMsg.len != 0); // TLS1.3 Ciphertext Handshake Messages Are Out of Order, Causing Decryption Failure ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_BAD_RECORD_MAC); ALERT_Info alert = { 0 }; ALERT_GetInfo(client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_BAD_RECORD_MAC); EXIT: CleanRecordBody(&recvframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ bool g_client = false; static void Test_NoServerCertPackAndParse001(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_VERIFY); if (ctx->isClient == g_client) { FRAME_CleanMsg(&frameType, &frameMsg); SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_GetDefaultMsg(&frameType, &frameMsg) == HITLS_SUCCESS); } memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NO_CERTVERIFY_FUNC_TC001 * @spec * 1. Enable the dual-end verification, make the CertificateVerify message sent by the server lose, and observe the * client behavior. Expected result: The client sends an alert message and the connection is disconnected. * 2. Enable the dual-end verification, make the CertificateVerify message sent by the client lose, and observe the * client behavior. Expected result: The client sends an alert message and the connection is disconnected. * @brief Servers MUST send this message when authenticating via a certificate. * Clients MUST send this message whenever authenticating via a certificate. * 4.4.3. Certificate Verify row 145 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NO_CERTVERIFY_FUNC_TC001(int isClient) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; g_client = (bool)isClient; /* 1. Enable the dual-end verification, make the CertificateVerify message sent by the server lose, and * observe the client behavior. * 2. Enable the dual-end verification, make the CertificateVerify message sent by the client lose, and observe * the client behavior. */ RecWrapper wrapper = {TRY_RECV_CERTIFICATE_VERIFY, REC_TYPE_HANDSHAKE, true, NULL, Test_NoServerCertPackAndParse001}; RegisterWrapper(wrapper); config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_NoCertificateSignPackAndParse001(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_VERIFY); if (ctx->isClient == g_client) { FRAME_CertificateVerifyMsg *certVerify = &frameMsg.body.hsMsg.body.certificateVerify; certVerify->signHashAlg.data = CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256; certVerify->signHashAlg.state = ASSIGNED_FIELD; } memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CERTVERIFY_SIGN_FUNC_TC001 * @spec * 1. Enable the dual-end verification, modify the signature field in the CertificateVerify message sent by the server, * and observe the client behavior. The expected result is that the client sends decrypt_error and the connection is * disconnected. * 2. Enable dual-end verification, modify the signature field in the CertificateVerify message sent by the client, and * observe the server behavior. Expected result: The server sends decrypt_error and disconnects the connection. * @brief The receiver of a CertificateVerify message MUST verify the signature field. * 4.4.3. Certificate Verify row 151 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CERTVERIFY_SIGN_FUNC_TC001(int isClient) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; g_client = (bool)isClient; RecWrapper wrapper = { TRY_SEND_CERTIFICATE_VERIFY, REC_TYPE_HANDSHAKE, false, NULL, Test_NoCertificateSignPackAndParse001 }; RegisterWrapper(wrapper); FRAME_CertInfo serverCertInfo = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; FRAME_CertInfo clientCertInfo = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &serverCertInfo); ASSERT_TRUE(server != NULL); client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &clientCertInfo); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_PARSE_UNSUPPORT_SIGN_ALG); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_FinishedPackAndParse001(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, FINISHED); if (ctx->isClient == g_client) { FRAME_FinishedMsg *finishMsg = &frameMsg.body.hsMsg.body.finished; finishMsg->verifyData.state = ASSIGNED_FIELD; finishMsg->verifyData.size = finishMsg->verifyData.size - 1; } memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_FINISHEDMSG_ERR_FUNC_TC001 * @spec * 1. Modify the Finished message sent by the server and observe the client behavior. The expected result is that the * client sends a decrypt_error message and the connection is disconnected. * 2. Modify the Finished message sent by the client and observe the server behavior. The expected result is that the * server sends a decrypt_error message and the connection is disconnected. * @brief Recipients of Finished messages MUST verify that the contents are correct * and if incorrect MUST terminate the connection with a "decrypt_error" alert. * 4.4.4. Finished row 153 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_FINISHEDMSG_ERR_FUNC_TC001(int isClient) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; g_client = (bool)isClient; RecWrapper wrapper = {TRY_SEND_FINISH, REC_TYPE_HANDSHAKE, false, NULL, /* 1. Modify the Finished message sent by the server and observe the client behavior. The expected result is * that the client sends a decrypt_error message and the connection is disconnected. * 2. Modify the Finished message sent by the client and observe the server behavior. */ Test_FinishedPackAndParse001}; RegisterWrapper(wrapper); config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RSA1024CERT_FUNC_TC001 * @spec * 1. Initialize the client and server to TLS1.3 and use the 1024-bit RSA certificate. The certificate verification * fails and connection establishment fails. * @brief Applications SHOULD also enforce minimum and maximum key sizes. For example, * certification paths containing keys or signatures weaker than 2048-bit RSA or 224-bit * ECDSA are not appropriate for secure applications. * Appendix C. Implementation Notes row 238 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RSA1024CERT_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo serverCertInfo = { "rsa_1024/rsa_root.crt", "rsa_1024/rsa_intCa.crt", "rsa_1024/rsa_dev.crt", 0, "rsa_1024/rsa_dev.key", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; const int32_t level = 2; HITLS_CFG_SetSecurityLevel(config, level); server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &serverCertInfo); ASSERT_TRUE(server == NULL); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_AlertPackAndParse004(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_ALERT; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.recType.data, REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &frameMsg.body.alertMsg; ASSERT_EQ(alertMsg->alertLevel.data, ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_BAD_CERTIFICATE); memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CERTCHAIN_FUNC_TC001 * @spec * 1, If no certificate is set on the server, the client sends a complete certificate chain, and the connection fails to be * established. * @brief Because certificate validation requires that trust anchors be distributed independently, * a certificate that specifies a trust anchor MAY be omitted from the chain, provided that supported * peers are known to possess any omitted certificates. * 4.4.2. Certificate row 119 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CERTCHAIN_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { 0, "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; RecWrapper wrapper = {HS_STATE_BUTT, REC_TYPE_ALERT, false, NULL, Test_AlertPackAndParse004}; RegisterWrapper(wrapper); config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CERTCHAIN_FUNC_TC002 * @spec * 1. The root certificate (any algorithm) is set on the server. The client sends a certificate chain that does not * contain the root certificate. The connection is successfully set up. * 2. The root certificate (any algorithm) is set on the client. The server sends a certificate chain without the root * certificate. The connection is successfully set up. * @brief Because certificate validation requires that trust anchors be distributed independently, * a certificate that specifies a trust anchor MAY be omitted from the chain, provided that supported * peers are known to possess any omitted certificates. * 4.4.2. Certificate row 119 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CERTCHAIN_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo serverCertInfo = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; FRAME_CertInfo clientCertInfo = { "ecdsa/ca-nist521.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &serverCertInfo); ASSERT_TRUE(server != NULL); client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &clientCertInfo); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CERTCHAIN_FUNC_TC003 * @spec * 1. The root certificate is incorrectly set on the server. After the client sends a complete certificate chain, the * connection fails to be established and the error code is displayed. ALERT_BAD_CERTIFICATE * @brief Because certificate validation requires that trust anchors be distributed independently, * a certificate that specifies a trust anchor MAY be omitted from the chain, provided that supported * peers are known to possess any omitted certificates. * 4.4.2. Certificate row 119 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_CERTCHAIN_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "rsa_sha/ca-3072.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", 0, "ecdsa/end256-sha256.key.der", 0, }; RecWrapper wrapper = { HS_STATE_BUTT, REC_TYPE_ALERT, true, NULL, Test_AlertPackAndParse004 }; RegisterWrapper(wrapper); config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTNULL_FUNC_TC001 * @spec If the client does not send any certificates (i.e., it sends an empty Certificate message), the server MAY at its discretion either continue the handshake without client authentication or abort the handshake with a "certificate_required" alert. * @title The certificate list of the server is not empty. The certificate of the peer end cannot be empty. The client sends an empty certificate. * Expected result: The handshake between the two parties fails, and the server sends an alarm. The alarm level is ALERT_LEVEL_FATAL and the description is certificate_required. * @precon nan * @brief 4.4.2.4. Receiving a Certificate Message row142 1. Enable dual-end verification. Do not allow the peer certificate to be empty, set the client certificate to be empty, and establish a connection. * @expect 1. If the connection fails to be established, the server generates an alarm. The alarm level is ALERT_LEVEL_FATAL and the description is certificate_required. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CLIENT_CERTNULL_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "ecdsa/ca-nist521.der", 0, 0, 0, 0, 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); ALERT_Info alert = { 0 }; ALERT_GetInfo(server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_CERTIFICATE_REQUIRED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ECDSA_SIGN_RSA_CERT_FUNC_TC001 * @spec Note that a certificate containing a key for one signature algorithm MAY be signed * using a different signature algorithm (for instance, an RSA key signed with an ECDSA key). * @title Apply for an RSA certificate issued by the ECDSA, set the certificate on the server, and set up a connection. Expected result: The connection is successfully set up. * @precon nan * @brief 4.4.2.4. Receiving a Certificate Message row144 1. Enable dual-end verification, apply for an RSA certificate issued by the ECDSA, set the certificate on the server, and set up a connection. * @expect 1. The connection is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ECDSA_SIGN_RSA_CERT_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_CertInfo certInfo = { "ecdsa_rsa_cert/rootCA.der", "ecdsa_rsa_cert/CA1.der", "ecdsa_rsa_cert/ee.der", 0, "ecdsa_rsa_cert/ee.key.der", 0, }; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; config->isSupportClientVerify = true; config->isSupportNoClientCert = false; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MD5_CERT_TC001 * @spec Apply for the ee certificate signed by the MD5 signature algorithm, set the MD5 certificate at both ends, * set up a link, and observe the server behavior. * Expected result: The server cannot select a proper certificate, sends bad_certificate, and disconnects the link. * @title * @precon nan * @brief 4.4.2.4. Receiving a Certificate Message row143 Any endpoint receiving any certificate which it would need to validate using any signature algorithm using an MD5 hash MUST abort the handshake with a "bad_certificate" alert. * @expect 1. The link is set up successfully. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MD5_CERT_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, true); FRAME_CertInfo certInfo = { "md5_cert/rsa_root.der", "md5_cert/rsa_intCa.der", "md5_cert/md5_dev.der", 0, "md5_cert/md5_dev.key", 0, }; FRAME_LinkObj *server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); FRAME_LinkObj *client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_CERT_CTRL_ERR_GET_SIGN_ALGO); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(client->ssl, &alertInfo); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, ALERT_BAD_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_cert.c
C
unknown
84,003
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "rec_wrapper.h" #include "cert.h" #include "securec.h" #include "process.h" #include "conn_init.h" #include "hitls_crypt_init.h" #include "hitls_psk.h" #include "common_func.h" #include "alert.h" #include "bsl_sal.h" /* END_HEADER */ #define MAX_BUF 16384 typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; } ResumeTestInfo; static int32_t DoHandshake(ResumeTestInfo *testInfo) { HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); testInfo->client = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } if (testInfo->clientSession != NULL) { int32_t ret = HITLS_SetSession(testInfo->client->ssl, testInfo->clientSession); if (ret != HITLS_SUCCESS) { return ret; } } testInfo->server = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } return FRAME_CreateConnection(testInfo->client, testInfo->server, true, HS_STATE_BUTT); } static void Test_PskGetCert(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { static uint8_t certBuf[MAX_BUF] = {0}; static uint32_t bufLen = 0; (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; if (user != NULL) { // cert message ASSERT_EQ(memcpy_s(certBuf, MAX_BUF, data, *len), EOK); bufLen = *len; } else { ASSERT_EQ(memcpy_s(data, bufSize, certBuf, bufLen), EOK); *len = bufLen; } EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_CERT_FUNC_TC001 * @spec - * When the @title psk session is resumed, the server sends the certificate message after sending the server hello * message. The expected handshake fails. * @precon nan * @brief 2.2 Resumption and Pre-Shared Key line 7 * @expect 1. The expected handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_CERT_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, &wrapper, Test_PskGetCert}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; wrapper.ctrlState = TRY_SEND_FINISH; wrapper.userData = NULL; RegisterWrapper(wrapper); ASSERT_NE(DoHandshake(&testInfo), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC001 * @spec - * @title Set the client and server to tls1.3. Set the cipher suites on the client and server to mismatch. As a result, * the expected connection establishment fails and a handshake_failure alert message is sent. * @precon nan * @brief 4.1.1. Cryptographic Negotiation line 13 * @expect 1. Expected handshake failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); cipherSuite = HITLS_AES_256_GCM_SHA384; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_HANDSHAKE_FAILURE); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_PskGetCertReq(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { static uint8_t certBuf[READ_BUF_SIZE] = {0}; static uint32_t bufLen = 0; (void)ctx; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; if (user != NULL) { // cert message ASSERT_EQ(memcpy_s(certBuf, READ_BUF_SIZE, data, *len), EOK); bufLen = *len; } else { ASSERT_EQ(memcpy_s(data, bufSize, certBuf, bufLen), EOK); *len = bufLen; } EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_CERTREQ_FUNC_TC001 * @spec - * @title 1. Preset the PSK. After the server sends the encryption extension, construct the certficaterequest message and * observe the client behavior. * @precon nan * @brief 4.3.2. Certificate Request line 110 * @expect 1. The client sends an alert message and disconnects the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_CERTREQ_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.config->isSupportClientVerify = true; RecWrapper wrapper = {TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, &wrapper, Test_PskGetCertReq}; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; wrapper.ctrlState = TRY_SEND_FINISH; wrapper.userData = NULL; RegisterWrapper(wrapper); ASSERT_EQ(DoHandshake(&testInfo), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC002 * @spec - * @title Set the client and server to tls1.3. Set the group on the client and server to different values. If the * expected connection establishment fails, the handshake_failurealert message is sent. * @precon nan * @brief 4.1.1. Cryptographic Negotiation line 13 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t group = HITLS_EC_GROUP_SECP256R1; HITLS_CFG_SetGroups(testInfo.config, &group, 1); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); group = HITLS_EC_GROUP_SECP384R1; HITLS_CFG_SetGroups(testInfo.config, &group, 1); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_HANDSHAKE_FAILURE); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC003 * @spec - * @title Set the client server to tls1.3 and the server certificate does not match the signature algorithm specified by * the client. In this case, the connection establishment fails and a handshake_failure alert message is sent. * @precon nan * @brief 4.1.1. Cryptographic Negotiation line 13 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC003() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t signature = CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256; HITLS_CFG_SetSignature(testInfo.config, &signature, 1); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); signature = CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384; HITLS_CFG_SetSignature(testInfo.config, &signature, 1); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_HANDSHAKE_FAILURE); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_ClientHelloMissKeyShare(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.keyshares.exState = MISSING_FIELD; frameMsg.body.hsMsg.body.clientHello.supportedGroups.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); ASSERT_NE(parseLen, *len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC004 * @spec - * @title Set the client server to tls1.3 and set the client psk mode to psk only. The provided psk server does not * support the psk. As a result, the connection fails to be established. Send handshake_failure alert * @precon nan * @brief 4.1.1. Cryptographic Negotiation line 13 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC004() { FRAME_Init(); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHelloMissKeyShare}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_HANDSHAKE_FAILURE); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC005 * @spec - * @title Set the client server to tls1.3 and set the psk mode of the client to psk only. No psk extension is provided. * As a result, connection establishment fails. Send handshake_failure alert * @precon nan * @brief 4.1.1. Cryptographic Negotiation line 13 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_MISMATCH_FUNC_TC005() { FRAME_Init(); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ClientHelloMissKeyShare}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_MISSING_EXTENSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_ErrorOrderPsk(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.extensionLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.length.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.pskModes.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); uint8_t pskMode[] = {0, 0x2d, 0, 2, 1, 1}; // psk with dhe mode ASSERT_NE(parseLen, *len); ASSERT_EQ(memcpy_s(&data[*len], bufSize - *len, &pskMode, sizeof(pskMode)), EOK); *len += sizeof(pskMode); ASSERT_EQ(parseLen, *len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC001 * @spec - * @title Set the client server to tls1.3 and construct the clienthello pre_shared_key extension that is not the last. * The server is expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC001() { FRAME_Init(); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ErrorOrderPsk}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_RepeatClientHelloExtension(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FieldState *extensionState = GetDataAddress(&frameMsg, user); *extensionState = DUPLICATE_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); ASSERT_NE(parseLen, *len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void RepeatClientHelloExtension(void *memberAddress, bool isPsk) { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); if (isPsk) { uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); } char serverName[] = "testServer"; uint8_t alpn[6] = {4, '1', '2', '3', '4', 0}; HITLS_CFG_SetServerName(testInfo.config, (uint8_t *)serverName, strlen(serverName)); HITLS_CFG_SetAlpnProtos(testInfo.config, alpn, strlen((char *)alpn)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, memberAddress, Test_RepeatClientHelloExtension}; RegisterWrapper(wrapper); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC002 * @spec - * @title The client server is tls1.3. Two signature algorithms are used to construct the clienthello. The server is * expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC002() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.signatureAlgorithms.exState, false); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC003 * @spec - * @title The client server is tls1.3. Two supportedGroups are displayed in the clienthello. The server is expected to * return an alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC003() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.supportedGroups.exState, false); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC004 * @spec - * @title The client server is tls1.3. Two pointFormats are displayed in the constructed clienthello. The server is * expected to return an alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC004() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.pointFormats.exState, false); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC005 * @spec - * @title The client server is tls1.3. Two supportedVersion fields are displayed in the clienthello. The server is expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC005() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.supportedVersion.exState, false); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC006 * @spec - * @title The client server is tls1.3. When two extendedMasterSecrets are displayed in the clienthello message, the * server is expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC006() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.extendedMasterSecret.exState, false); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC007 * @spec - * @title The client server is tls1.3. Two pskModes are displayed in the clienthello. The server is expected to return an * alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC007() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.pskModes.exState, true); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC008 * @spec - * @title The client server is tls1.3. Two keyshares are displayed when the clienthello is constructed. The server is * expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC008() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.keyshares.exState, false); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC009 * @spec - * @title The client server is tls1.3. Two psks are displayed when the clienthello is constructed. The server is expected * to return an alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC009() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.psks.exState, true); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC010 * @spec - * @title The client server is tls1.3. Two serverNames are displayed in the clienthello. The server is expected to return * alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC010() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.serverName.exState, false); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC011 * @spec - * @title The client server is tls1.3. Two alpn extensions are displayed when the clienthello is constructed. The server is expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC011() { RepeatClientHelloExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.alpn.exState, false); } /* END_CASE */ static void Test_RepeatServerHelloExtension(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); FieldState *extensionState = GetDataAddress(&frameMsg, user); *extensionState = DUPLICATE_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC012 * @spec - * @title The client server is tls1.3. Two supportedversion extensions are displayed when the serverhello is * constructed. The client is expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC012() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &((FRAME_Msg *)0)->body.hsMsg.body.serverHello.supportedVersion.exState, Test_RepeatServerHelloExtension}; RegisterWrapper(wrapper); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC013 * @spec - * @title The client server is tls1.3. Two key_share extensions are displayed when the serverhello is constructed. The * client is expected to return alert. * @precon nan * @brief 4.2. Extensions line 40 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_ERR_HEELO_FUNC_TC013() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.version = HITLS_VERSION_TLS13; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &((FRAME_Msg *)0)->body.hsMsg.body.serverHello.keyShare.exState, Test_RepeatServerHelloExtension}; RegisterWrapper(wrapper); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC002 * @spec - * @title 1. Set the client to tls1.2 and the server to tls1.3. Initiate a connection establishment request. The expected * connection establishment is successful and the negotiated version is tls1.2. * @precon nan * @brief 4.2.1 Supported Versions line 42 * @expect 1. The expected connection setup is successful and the negotiated version is tls1.2. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.version = HITLS_VERSION_TLS13; testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_FreeConfig(testInfo.config); testInfo.config = HITLS_CFG_NewTLS12Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint16_t version = 0; ASSERT_EQ(HITLS_GetNegotiatedVersion(testInfo.client->ssl, &version), HITLS_SUCCESS); ASSERT_EQ(version, HITLS_VERSION_TLS12); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_ErrLegacyVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.version.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.version.data = HITLS_VERSION_TLS13; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC003 * @spec - * @title 1. Set the client to tls1.2 and server to tls1.3, initiate a connection establishment request, change the * version value in the client hello message to 0x0304, and expect the server to stop handshake. * @precon nan * @brief 4.2.1 Supported Versions line 42 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC003() { FRAME_Init(); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ErrLegacyVersion}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_FreeConfig(testInfo.config); testInfo.config = HITLS_CFG_NewTLS12Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(testInfo.client->ssl->negotiatedInfo.version == HITLS_VERSION_TLS12); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC004 * @spec - * @title 1. Set the client to support TLS1.1 and TLS1.0 and the server to support TLS1.3. Initiate a connection * establishment request. The server is expected to negotiate TLS1.3. * @precon nan * @brief 4.2.1 Supported Versions line 43 * @expect 1. The expected connection setup is successful and the negotiated version is tls1.3. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC004() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.version = HITLS_VERSION_TLS13; testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint16_t version = 0; ASSERT_EQ(HITLS_GetNegotiatedVersion(testInfo.client->ssl, &version), HITLS_SUCCESS); ASSERT_EQ(version, HITLS_VERSION_TLS13); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_UnknownVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientHello.supportedVersion.exData.data); uint16_t version[] = { 0x01, 0x02, *(uint16_t *)user }; frameMsg.body.hsMsg.body.clientHello.supportedVersion.exData.data = BSL_SAL_Calloc(sizeof(version) / sizeof(uint16_t), sizeof(uint16_t)); ASSERT_EQ(memcpy_s(frameMsg.body.hsMsg.body.clientHello.supportedVersion.exData.data, sizeof(version), version, sizeof(version)), EOK); frameMsg.body.hsMsg.body.clientHello.supportedVersion.exData.size = sizeof(version) / sizeof(uint16_t); frameMsg.body.hsMsg.body.clientHello.supportedVersion.exData.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.supportedVersion.exDataLen.data = sizeof(version); frameMsg.body.hsMsg.body.clientHello.supportedVersion.exLen.data = sizeof(version) + sizeof(uint8_t); memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC005 * @spec - * @title 1. Set the client server to tls1.3 and modify the supportedversion field in the client hello packet, * An invalid version number 0x0001,0x0002 is added before tils1.3. It is expected that the server can * negotiate the TLS1.3 version. * @precon nan * @brief 4.2.1 Supported Versions line 43 * @expect 1. The expected connection setup is successful and the negotiated version is tls1.3. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC005() { FRAME_Init(); uint16_t version = HITLS_VERSION_TLS13; RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, &version, Test_UnknownVersion}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); version = 0; ASSERT_EQ(HITLS_GetNegotiatedVersion(testInfo.client->ssl, &version), HITLS_SUCCESS); ASSERT_EQ(version, HITLS_VERSION_TLS13); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC006 * @spec - * @title 1. Configure the TLS1.2 client and TLS1.3 server, and construct the clienthello message that carries the * supportedversion extension. If the value is 0x0303 and 0x0302, the server negotiates TLS1.2 normally and * the handshake succeeds. * @precon nan * @brief 4.2.1 Supported Versions line 44 * @expect 1. The expected connection setup is successful and the negotiated version is tls1.2. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC006() { FRAME_Init(); uint16_t version = HITLS_VERSION_TLS12; RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, &version, Test_UnknownVersion }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_FreeConfig(testInfo.config); testInfo.config = HITLS_CFG_NewTLS12Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); version = 0; ASSERT_EQ(HITLS_GetNegotiatedVersion(testInfo.client->ssl, &version), HITLS_SUCCESS); ASSERT_EQ(version, HITLS_VERSION_TLS12); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_ServerVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); if (*(uint16_t *)user == 0) { ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.supportedVersion.exState, MISSING_FIELD); } else if (*(uint16_t *)user == HITLS_VERSION_TLS13) { ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.version.data, HITLS_VERSION_TLS12); ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.supportedVersion.data.data, HITLS_VERSION_TLS13); } else if (*(uint16_t *)user == HITLS_VERSION_TLS12) { frameMsg.body.hsMsg.body.serverHello.supportedVersion.exState = INITIAL_FIELD; frameMsg.body.hsMsg.body.serverHello.supportedVersion.exLen.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.serverHello.supportedVersion.exLen.data = 0; frameMsg.body.hsMsg.body.serverHello.supportedVersion.exType.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.serverHello.supportedVersion.exType.data = HS_EX_TYPE_SUPPORTED_VERSIONS; frameMsg.body.hsMsg.body.serverHello.supportedVersion.data.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.serverHello.supportedVersion.data.data = HITLS_VERSION_TLS12; } else { ASSERT_EQ(0, 1); } memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC007 * @spec - * @title 1. Set the client to TLS1.2 and server to TLS1.3. The earlier version of TLS1.2 is expected to be negotiated. * The server hello message sent does not carry the supportedversion extension. * @precon nan * @brief 4.2.1 Supported Versions line 45 * @expect 1. The expected connection setup is successful and the negotiated version is tls1.2. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC007() { FRAME_Init(); uint16_t version = 0; RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &version, Test_ServerVersion}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_FreeConfig(testInfo.config); testInfo.config = HITLS_CFG_NewTLS12Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); version = 0; ASSERT_EQ(HITLS_GetNegotiatedVersion(testInfo.client->ssl, &version), HITLS_SUCCESS); ASSERT_EQ(version, HITLS_VERSION_TLS12); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CHECK_SERVERHELLO_MASTER_SECRET_FUNC_TC001 * @spec * The client does not support the extended master key and performs negotiation. After receiving the server hello * message with the extended master key, the client sends an alert message. Check whether the two parties enter the * alerted state, and the read and write operations fail. * @brief When an error is detected, the detecting party sends a message to its peer. Upon transmission or receipt of a * fatal alert message, both parties MUST immediately close the connection. * 6.2.0. Alert Protocol row 216 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CHECK_SERVERHELLO_MASTER_SECRET_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); HITLS_CFG_SetExtenedMasterSecretSupport(testInfo.c_config, true); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_ServerHelloSessionId(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.sessionIdSize.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.sessionIdSize.data = *len; memset_s(data, bufSize, 0, bufSize); ASSERT_EQ(parseLen, *len); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMESH_SESSIONId_LENGTHERR_FUNC_TC001 * @spec * 1. Session recovery. If the client receives a ServerHello message whose session_id length exceeds the length of the * entire packet, the client sends a decode_error alarm and the session recovery fails. * @brief Peers which receive a message which cannot be parsed according to the syntax (e.g., * have a length extending beyond the message boundary or contain an out-of-range length) * MUST terminate the connection with a "decode_error" alert. * 6. Alert Protocol row 209 */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RESUMESH_SESSIONId_LENGTHERR_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerHelloSessionId}; testInfo.config = HITLS_CFG_NewTLS13Config(); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_DECODE_ERROR); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC008 * @spec - * @title 1. Set the client to tls1.2 and server to tls1.3. Construct the serverhello message that carries the supportedversion extension. tls1.2 in the extension, the client is expected to abort the negotiation, * @precon nan * @brief 4.2.1 Supported Versions line 45 * @expect 1. The expected connection setup is successful and the negotiated version is tls1.3. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC008() { FRAME_Init(); uint16_t version = HITLS_VERSION_TLS12; RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &version, Test_ServerVersion}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS12Config(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_FreeConfig(testInfo.config); testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC009 * @spec - * @title Set the client server to tls1.3, set up a connection normally, and the serverhello message is expected to carry the * supportedversion extension. The value contains only 0x0304, and the value of legacy_version is 0x0303. * @precon nan * @brief 4.2.1 Supported Versions line 45 * @expect 1. The expected connection setup is successful and the negotiated version is tls1.3. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC009() { FRAME_Init(); uint16_t version = HITLS_VERSION_TLS13; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &version, Test_ServerVersion }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); version = 0; ASSERT_EQ(HITLS_GetNegotiatedVersion(testInfo.client->ssl, &version), HITLS_SUCCESS); ASSERT_EQ(version, HITLS_VERSION_TLS13); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_ErrorServerVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); if (*(uint16_t *)user == 0) { frameMsg.body.hsMsg.body.serverHello.supportedVersion.exState = MISSING_FIELD; } else if (*(uint16_t *)user == HITLS_VERSION_TLS13) { frameMsg.body.hsMsg.body.serverHello.version.data = HITLS_VERSION_TLS13; } else if (*(uint16_t *)user == HITLS_VERSION_TLS12) { frameMsg.body.hsMsg.body.serverHello.supportedVersion.data.data = HITLS_VERSION_TLS12; } else { ASSERT_EQ(0, 1); } memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void ErrorServerVersion(uint16_t version) { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &version, Test_ErrorServerVersion }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLSConfig(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); if (version == HITLS_VERSION_TLS12) { ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); } EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC0010 * @spec - * @title 1. Set the client server to tls1.3, construct the legacy_version value of serverhello to 0x0304, and expect the * client to stop connection establishment. * @precon nan * @brief 4.2.1 Supported Versions line 45 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC0010() { ErrorServerVersion(HITLS_VERSION_TLS13); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC0011 * @spec - * @title 1. Set the client server to tls1.3 and construct that the supportedversion parameter of the serverhello does * not exist. The client is expected to stop connection establishment. * @precon nan * @brief 4.2.1 Supported Versions line 45 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC0011() { ErrorServerVersion(0); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC0012 * @spec - * @title 1. Set the client server to tls1.3 and set the supportedversion value of the serverhello to tls1.2. Expect the * client to stop connection establishment. The client is expected to send the illegal_parameter alarm. * @precon nan * @brief 4.2.1 Supported Versions line 45/47 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SUPPORT_VERSION_FUNC_TC0012() { ErrorServerVersion(HITLS_VERSION_TLS12); } /* END_CASE */ static void Test_AbsentGroup(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; (void)bufSize; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); uint32_t sz = frameMsg.body.hsMsg.body.clientHello.supportedGroups.exData.size; ASSERT_TRUE(sz > 1); frameMsg.body.hsMsg.body.clientHello.supportedGroups.exData.size = 1; frameMsg.body.hsMsg.body.clientHello.supportedGroups.exData.data[0] = frameMsg.body.hsMsg.body.clientHello.supportedGroups.exData.data[1]; frameMsg.body.hsMsg.body.clientHello.supportedGroups.exDataLen.data = sizeof(uint16_t); memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC001 * @spec - * @title 1. Initialize the client server to tls1.3, and construct that the keyshareentry.group in the sent client hello * message is not contained in the supported_group of the client. The server aborts the handshake and returns * the illegal_parameter alarm. * @precon nan * @brief 4.2.8 key share line 68 * @expect 1. Expected connection establishment failure * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC001() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_AbsentGroup }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void HelloRetryRequest(WrapperFunc func) { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_HELLO_RETRY_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, func }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } static void Test_HelloRetryRequest(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; (void)bufSize; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data = HITLS_EC_GROUP_SECP384R1; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC002 * @spec - * @title 1. Initialize the client and server to tls1.3 and construct the scenario of sending hrr messages. * Construct the scenario where the selected_group in the hrr message is not in the group supported by the * client. Expect the client to terminate the handshake and return the illegal_parameter alarm. * @precon nan * @brief 4.2.8 key share line 69 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC002() { HelloRetryRequest(Test_HelloRetryRequest); } /* END_CASE */ static void Test_HelloRetryRequestSameGroup(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; (void)bufSize; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data, HITLS_EC_GROUP_SECP256R1); frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data = HITLS_EC_GROUP_CURVE25519; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC003 * @spec - * @title 1. Initialize the client server to tls1.3, construct the scenario of sending hrr messages, and construct the * group corresponding to the key_share key provided by the client. The client terminates the handshake and * returns the illegal_parameter alarm. * @precon nan * @brief 4.2.8 key share line 69 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC003() { HelloRetryRequest(Test_HelloRetryRequestSameGroup); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC004 * @spec - * @title 1. Initialize the client and server to tls1.3 and construct the scenario of sending hrr messages. * Construct the scenario where the key_share carried in the clienthello message sent again is not the * selected_group specified in the hrr message. The server is expected to terminate the handshake and return * the illegal_parameter alarm. * @precon nan * @brief 4.2.8 key share line 71 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEY_SHARE_FUNC_TC004() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_HELLO_RETRY_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_HelloRetryRequest }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC001 * @spec - * @title 1. The client initiates connection establishment by using the PSK encrypted by the unknown key. * Expected result: A non-PSK handshake is performed. * @precon nan * @brief 4.2.9 pre-shared key exchange line 96 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; HITLS_CFG_FreeConfig(testInfo.config); testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(testInfo.client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 0); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_InvalidSelectedIdentity(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; (void)bufSize; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.pskSelectedIdentity.exState, INITIAL_FIELD); frameMsg.body.hsMsg.body.serverHello.pskSelectedIdentity.data.data = 1; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC002 * @spec - * @title 1. In the first handshake, the selected_identity of the server is not in the identity list provided by the * client, The client uses the illegal_parameter alarm to terminate the handshake. As a result, the first * connection fails to be established. * @precon nan * @brief 4.2.9 pre-shared key exchange line 100 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC002() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_InvalidSelectedIdentity }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC003 * @spec - * @title 1. During session restoration, the selected_identity of the server is not in the identity list provided by the * client, The client uses the illegal_parameter alarm to terminate the handshake. As a result, the first * connection fails to be established. * @precon nan * @brief 4.2.9 pre-shared key exchange line 100 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC003() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_InvalidSelectedIdentity }; RegisterWrapper(wrapper); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_InvalidCipherSuites(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; (void)bufSize; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); ASSERT_EQ(frameMsg.body.hsMsg.body.serverHello.pskSelectedIdentity.exState, INITIAL_FIELD); frameMsg.body.hsMsg.body.serverHello.cipherSuite.data = HITLS_AES_256_GCM_SHA384; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC004 * @spec - * @title 1. In the first handshake, the hash algorithm in the cipher suite selected by the server does not match the * PSK. The client uses the (overwritten) illegal_parameter alarm to terminate the handshake. As a result, the * onnection fails to be established. * @precon nan * @brief 4.2.9 pre-shared key exchange line 100 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC004() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_InvalidCipherSuites }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); HITLS_Connect(testInfo.client->ssl); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC005 * @spec - * @title 1. Preset the PSK. When the client sends the client hello message, the client parses the extension item of the * client hello message so that the pre_share_key extension is not the last extension and continues to * establish the connection. Expected result: The server returns ALERT illegal_parameter and the handshake is * interrupted. * @precon nan * @brief 4.2.9 pre-shared key exchange line 100 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC005() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ErrorOrderPsk }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC006 * @spec - * @title 1. During PSK-based session recovery, the client sends the client hello message, and parses the client hello * extension. Enable the pre_share_key extension not to establish a connection for the last extension. Expected * result: The server returns ALERT illegal_parameter and the handshake is interrupted. * @precon nan * @brief 4.2.9 pre-shared key exchange line 102 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC006() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ErrorOrderPsk }; RegisterWrapper(wrapper); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = { 0 }; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_ServerErrorOrderPsk(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.extensionLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.length.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.supportedVersion.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); uint8_t supportedVersion[] = {0, 0x2b, 0, 2, 3, 4}; ASSERT_NE(parseLen, *len); ASSERT_EQ(memcpy_s(&data[*len], bufSize - *len, &supportedVersion, sizeof(supportedVersion)), EOK); *len += sizeof(supportedVersion); ASSERT_EQ(parseLen, *len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC007 * @spec - * @title 1. Preset the PSK. When the server sends the server hello message, the server parses the extension item of the * server hello message so that the pre_share_key extension is not the last extension and continues to * establish the connection. Expected result: The session is restored successfully. * @precon nan * @brief 4.2.9 pre-shared key exchange line 100 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC007() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_CERTIFICATE_VERIFY, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerErrorOrderPsk }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC008 * @spec - * @title 1. During PSK-based session recovery, the server parses the extension items of the server hello message when * the server sends the server hello message, Make the pre_share_key extension not the last extension and * continue to establish the connection. Expected result: The session is restored successfully. * @precon nan * @brief 4.2.9 pre-shared key exchange line 102 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_FUNC_TC008() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerErrorOrderPsk }; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_HrrMisClientHelloExtension(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; if (ctx->hsCtx->haveHrr) { uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FieldState *extensionState = GetDataAddress(&frameMsg, user); *extensionState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); } EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void WithoutPskMisKeyExtension(void *memberAddress, bool isResume, bool isHrr) { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t clientGroups[] = {HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, clientGroups, sizeof(clientGroups) / sizeof(uint16_t)); if (isResume) { testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession); } else { testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); } if (isHrr) { uint16_t serverGroups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(testInfo.config, serverGroups, sizeof(serverGroups) / sizeof(uint16_t)); } testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); WrapperFunc func = isHrr ? Test_HrrMisClientHelloExtension : Test_MisClientHelloExtension; RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, memberAddress, func }; RegisterWrapper(wrapper); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_SUCCESS); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.server->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_MISSING_EXTENSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC001 * @spec - * @title 1. When the first connection is established, the first ClientHello message received by the server does not * contain the pre_shared_key extension. If signature_algorithms, supported_groups, or key_share is missing, * the connection fails to be established and the server reports the missing_extension alarm. * @precon nan * @brief 9.2 Mandatory-to-Implement Extensions line 233 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC001() { bool isResume = false; bool isHrr = false; WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.signatureAlgorithms.exState, isResume, isHrr); WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.supportedGroups.exState, isResume, isHrr); WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.keyshares.exState, isResume, isHrr); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC002 * @spec - * @title 1. Certificate handshake in the hrr scenario, second ClientHello * If signature_algorithms, supported_groups, or key_share is missing, the connection fails to be established and the * server reports the missing_extension alarm. * @precon nan * @brief 9.2 Mandatory-to-Implement Extensions line 233 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC002() { bool isResume = false; bool isHrr = true; WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.signatureAlgorithms.exState, isResume, isHrr); WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.supportedGroups.exState, isResume, isHrr); WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.keyshares.exState, isResume, isHrr); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC003 * @spec - * @title 1. When the first connection is established, the first ClientHello message received by the server does not * contain supported_groups. But include key_share, and vice versa. The connection fails to be established and * theserver generates the missing_extension alarm. * @precon nan * @brief 9.2 Mandatory-to-Implement Extensions line 233 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC003() { bool isResume = false; bool isHrr = false; WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.supportedGroups.exState, isResume, isHrr); WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.keyshares.exState, isResume, isHrr); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC004 * @spec - * @title 1. The session is resumed. The first ClientHello message received by the server does not contain * supported_groups, But include key_share, and vice versa. The session fails to be restored, and the server * generates the missing_extension alarm. * @precon nan * @brief 9.2 Mandatory-to-Implement Extensions line 233 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC004() { bool isResume = true; bool isHrr = false; WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.supportedGroups.exState, isResume, isHrr); WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.keyshares.exState, isResume, isHrr); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC005 * @spec - * @title 1. In the hrr scenario, the certificate handshake second ClientHello does not contain supported_groups. * share is contained, the connection fails to be established and the server generates the * missing_extension alarm. * @precon nan * @brief 9.2 Mandatory-to-Implement Extensions line 233 * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_EXTENSION_ASSOCIATION_FUNC_TC005() { bool isResume = false; bool isHrr = true; WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.supportedGroups.exState, isResume, isHrr); WithoutPskMisKeyExtension(&((FRAME_Msg *)0)->body.hsMsg.body.clientHello.keyshares.exState, isResume, isHrr); } /* END_CASE */ static void Test_CertificateExtensionError001(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); FrameCertItem *certItem = frameMsg.body.hsMsg.body.certificate.certItem; // status_request Certificate Allowed Extensions. type(2) + len(2) + ctx(len) uint8_t certExtension[] = {0x00, 0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00}; uint32_t extensionLen = sizeof(certExtension); uint8_t *extensionData = BSL_SAL_Calloc(extensionLen, sizeof(uint8_t)); ASSERT_TRUE(extensionData != NULL); ASSERT_EQ(memcpy_s(extensionData, extensionLen, certExtension, extensionLen), EOK); certItem->extension.state = ASSIGNED_FIELD; BSL_SAL_FREE(certItem->extension.data); certItem->extension.data = extensionData; certItem->extension.size = extensionLen; certItem->extensionLen.state = ASSIGNED_FIELD; certItem->extensionLen.data = extensionLen; *len += extensionLen; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CERT_EXTENSION_TC001 * @spec - * @title The test certificate message carries the extension of the response. However, due to the current feature not * being supported, requests will not be sent proactively. Expected to send illegal alerts and disconnect links. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the certificate message sent by the server to the client to include the status_request extension * 3. Establish a connection and observe client behavior * @expect * 1. Initialization successful * 2. Setup successful * 3. The client returns alert ALERT_ILLEGAL_PARAMETER. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CERT_EXTENSION_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.config->isSupportClientVerify = true; RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_CertificateExtensionError001}; RegisterWrapper(wrapper); HITLS_CFG_SetCheckKeyUsage(testInfo.config, false); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_CertificateExtensionError002(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); FrameCertItem *certItem = frameMsg.body.hsMsg.body.certificate.certItem; // signature_algorithm Certificate-recognized but disallowed extensions. type(2) + len(2) + ctx(len) uint8_t certExtension[] = {0x00, 0x0d, 0x00, 0x04, 0x00, 0x00, 0x08, 0x09}; uint32_t extensionLen = sizeof(certExtension); uint8_t *extensionData = BSL_SAL_Calloc(extensionLen, sizeof(uint8_t)); ASSERT_TRUE(extensionData != NULL); ASSERT_EQ(memcpy_s(extensionData, extensionLen, certExtension, extensionLen), EOK); certItem->extension.state = ASSIGNED_FIELD; BSL_SAL_FREE(certItem->extension.data); certItem->extension.data = extensionData; certItem->extension.size = extensionLen; certItem->extensionLen.state = ASSIGNED_FIELD; certItem->extensionLen.data = extensionLen; *len += extensionLen; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CERT_EXTENSION_TC002 * @spec - * @title The test certificate message carries identifiable but not allowed extensions. Expected to send illegal * alerts and disconnect. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the certificate message sent by the server to the client to include the signature_algorithm extension * 3. Establish a connection and observe client behavior * @expect * 1. Initialization successful * 2. Setup successful * 3. The client returns alert ALERT_ILLEGAL_PARAMETER. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CERT_EXTENSION_TC002() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.config->isSupportClientVerify = true; RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_CertificateExtensionError002}; RegisterWrapper(wrapper); HITLS_CFG_SetCheckKeyUsage(testInfo.config, false); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_CertificateExtensionError003(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); FrameCertItem *certItem = frameMsg.body.hsMsg.body.certificate.certItem; // Unrecognized Extensions. type(2) + len(2) + ctx(len) uint8_t certExtension[] = {0x00, 0x56, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00}; uint32_t extensionLen = sizeof(certExtension); uint8_t *extensionData = BSL_SAL_Calloc(extensionLen, sizeof(uint8_t)); ASSERT_TRUE(extensionData != NULL); ASSERT_EQ(memcpy_s(extensionData, extensionLen, certExtension, extensionLen), EOK); certItem->extension.state = ASSIGNED_FIELD; BSL_SAL_FREE(certItem->extension.data); certItem->extension.data = extensionData; certItem->extension.size = extensionLen; certItem->extensionLen.state = ASSIGNED_FIELD; certItem->extensionLen.data = extensionLen; *len += extensionLen; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CERT_EXTENSION_TC003 * @spec - * @title Test certificate message carrying unrecognized extensions. Expected to send illegal alerts and disconnect * @precon nan * @brief * 1. Apply and initialize config * 2. Set the certificate message sent by the server to the client to include the unrecognized extension * 3. Establish a connection and observe client behavior * @expect * 1. Initialization successful * 2. Setup successful * 3. The client returns alert ALERT_ILLEGAL_PARAMETER. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CERT_EXTENSION_TC003() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.config->isSupportClientVerify = true; RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_CertificateExtensionError003}; RegisterWrapper(wrapper); HITLS_CFG_SetCheckKeyUsage(testInfo.config, false); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); ALERT_Info alert = {0}; ALERT_GetInfo(testInfo.client->ssl, &alert); ASSERT_EQ(alert.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alert.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_extensions_1.c
C
unknown
100,938
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "rec_wrapper.h" #include "cert.h" #include "securec.h" #include "process.h" #include "conn_init.h" #include "hitls_crypt_init.h" #include "hitls_psk.h" #include "common_func.h" #include "alert.h" #include "bsl_sal.h" #include "hs_extensions.h" /* END_HEADER */ #define MAX_BUF 16384 typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; } ResumeTestInfo; static int32_t DoHandshake(ResumeTestInfo *testInfo) { HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); testInfo->client = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } if (testInfo->clientSession != NULL) { int32_t ret = HITLS_SetSession(testInfo->client->ssl, testInfo->clientSession); if (ret != HITLS_SUCCESS) { return ret; } } testInfo->server = FRAME_CreateLink(testInfo->config, testInfo->uioType); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } return FRAME_CreateConnection(testInfo->client, testInfo->server, true, HS_STATE_BUTT); } typedef enum { WITHOUT_PSK, PRE_CONFIG_PSK, SESSION_RESUME_PSK } PskStatus; static void Test_PskConnect(uint32_t serverMode, PskStatus pskStatus) { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY | TLS13_KE_MODE_PSK_WITH_DHE); if (pskStatus == SESSION_RESUME_PSK) { testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession); } else if (pskStatus == PRE_CONFIG_PSK) { uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); } else { testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); } HITLS_CFG_SetKeyExchMode(testInfo.config, serverMode); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(testInfo.client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, pskStatus == SESSION_RESUME_PSK ? 1 : 0); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC001 * @spec - * @title 1. Set key_exchange_mode to 3 on the client and server to establish a connection for the first time. * The expected result indicates that the connection is successfully established. * @precon nan * @brief psk Supplement the test case line 269. * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC001() { Test_PskConnect(TLS13_KE_MODE_PSK_ONLY | TLS13_KE_MODE_PSK_WITH_DHE, WITHOUT_PSK); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC002 * @spec - * @title 1. Set key_exchange_mode to 3 on the client and server to establish a connection for the first time. * The expected result indicates that the connection is successfully established. * @precon nan * @brief psk Supplement the test case line 269. * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC002() { Test_PskConnect(TLS13_KE_MODE_PSK_ONLY | TLS13_KE_MODE_PSK_WITH_DHE, PRE_CONFIG_PSK); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC003 * @spec - * @title 1. Restore the session. Set key_exchange_mode to 3 on the client and server. The client carries key_share and * connection. The expected result indicates that the connection is successfully established. * @precon nan * @brief psk Supplement the test case line 269. * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC003() { Test_PskConnect(TLS13_KE_MODE_PSK_ONLY | TLS13_KE_MODE_PSK_WITH_DHE, SESSION_RESUME_PSK); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC004 * @spec - * @title 1. Preset the PSK, set the key_exchange_mode of the client and server to 3 and set the key_exchange_mode of the * server to psk_only, and establish a connection. The expected result indicates that the connection is * successfully established. * @precon nan * @brief psk Supplement the test case line 269. * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC004() { Test_PskConnect(TLS13_KE_MODE_PSK_ONLY, PRE_CONFIG_PSK); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC005 * @spec - * @title 1. Restore the session. Set the key_exchange_mode of the client and server to 3. Set the key_share extended by * the client to establish a connection and enable the server to reject the PSK. Expected result: * The session fails and certificate authentication is rejected. * @precon nan * @brief psk Supplement the test case line 269. * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC005() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY | TLS13_KE_MODE_PSK_WITH_DHE); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_FreeConfig(testInfo.config); testInfo.config = HITLS_CFG_NewTLS13Config(); HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(testInfo.client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 0); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC006 * @spec - * @title 1. Preset the PSK and set the key_exchange_mode on the client server to 3. The key_share extension on the * client is lost and a connection is established. Expected result: The server sends an alert message and * the connection is disconnected. * @precon nan * @brief psk Added the test case line 269. * @expect 1. Expected connection establishment failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSK_MODES_FUNC_TC006() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, &((FRAME_Msg *)0)->body.hsMsg.body.clientHello.keyshares.exState, Test_MisClientHelloExtension }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY | TLS13_KE_MODE_PSK_WITH_DHE); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_NE(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CERTICATE_VERIFY_FAIL_FUNC_TC001 * @brief 6.3. Error Alerts row 216 * The client does not support extended master keys and performs negotiation. After receiving the server hello * message with the extended master keys, the client sends an alert message. Check whether the two parties enter the * alerted state, and the read and write operations fail. * */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CERTICATE_VERIFY_FAIL_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.s_config != NULL); testInfo.c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.c_config != NULL); HITLS_CFG_SetExtenedMasterSecretSupport(testInfo.c_config, false); testInfo.client = FRAME_CreateLink(testInfo.c_config, testInfo.uioType); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.s_config, testInfo.uioType); ASSERT_TRUE(testInfo.server != NULL); ASSERT_EQ(HITLS_SetSession(testInfo.client->ssl, testInfo.clientSession), HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.c_config); HITLS_CFG_FreeConfig(testInfo.s_config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ static void Test_Client_Mode(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.pskModes.exData.state = ASSIGNED_FIELD; BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientHello.pskModes.exData.data); uint16_t version[] = { 0x03, }; frameMsg.body.hsMsg.body.clientHello.pskModes.exData.data = BSL_SAL_Calloc(sizeof(version) / sizeof(uint8_t), sizeof(uint8_t)); ASSERT_EQ(memcpy_s(frameMsg.body.hsMsg.body.clientHello.pskModes.exData.data, sizeof(version), version, sizeof(version)), EOK); frameMsg.body.hsMsg.body.clientHello.keyshares.exState = MISSING_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.state = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKMODEZERO_FUNC_TC001 * @spec - * @title Initialize the client and server to tls1.3. Construct a scenario where the psk is carried but key_share is not * carried. Construct a scenario where the psk_mode carried in the clienthello message is 3. It is expected * that the handshake fails. * @precon nan * @brief 4.1.1. Cryptographic Negotiation line 11 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKMODEZERO_FUNC_TC001() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_Mode }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_MISSING_EXTENSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_Server_Keyshare(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.keyShare.data.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data = *(uint64_t *)user; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC001 * @spec - * @title Initialize the client server to tls1.3 and construct the selected_group carried in the key_share extension in * the sent serverhello message. If the group is not the keyshareentry group carried in the client hello message * but the group provided in the client hello message, the connection fails to be established. * @precon nan * @brief 4.2.8. Key Share line 72 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC001() { FRAME_Init(); uint64_t groupreturn[] = {HITLS_EC_GROUP_SECP384R1, }; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &groupreturn, Test_Server_Keyshare }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t group[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; HITLS_CFG_SetGroups(testInfo.config, group, 2); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_Server_Keyshare3(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); ASSERT_TRUE(frameMsg.body.hsMsg.body.serverHello.keyShare.exState == MISSING_FIELD); memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKKEYSHARE_FUNC_TC001 * @spec - * @title 1. Initialize the client and server to tls1.3 and construct a scenario where psk_ke is used. The expected * serverhello message sent does not carry the key_share extension. * @precon nan * @brief 4.2.8. Key Share line 73 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKKEYSHARE_FUNC_TC001() { FRAME_Init(); RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Server_Keyshare3 }; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ static void Test_Server_Keyshare4(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.keyShare.exState = INITIAL_FIELD; frameMsg.body.hsMsg.body.serverHello.keyShare.exLen.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.serverHello.keyShare.data.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data = HITLS_EC_GROUP_CURVE25519; FRAME_ModifyMsgInteger(HS_EX_TYPE_KEY_SHARE, &frameMsg.body.hsMsg.body.serverHello.keyShare.exType); uint8_t uu[] = {0x3b, 0xb5, 0xe4, 0x3c, 0xf6, 0xc4, 0x70, 0x0f, 0x3c, 0x7f, 0x05, 0x0b, 0xd4, 0xfb, 0x24, 0x39, 0xc8, 0xb6, 0x13, 0x50, 0xc6, 0xee, 0xde, 0x69, 0xc5, 0x09, 0xef, 0x2e, 0x21, 0x4d, 0xd8, 0x1e}; FRAME_ModifyMsgArray8(uu, sizeof(uu), &frameMsg.body.hsMsg.body.serverHello.keyShare.data.keyExchange, &frameMsg.body.hsMsg.body.serverHello.keyShare.data.keyExchangeLen); memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKKEYSHARE_FUNC_TC002 * @spec - * @title 1. Initialize the client and server to tls1.3, construct the psk_ke scenario, and construct the sent * serverhello message carrying the key_share extension. It is expected that the connection fails to be * established. * @precon nan * @brief 4.2.8. Key Share line 73 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKKEYSHARE_FUNC_TC002() { FRAME_Init(); RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Server_Keyshare4}; RegisterWrapper(wrapper); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(testInfo.config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY); HITLS_CFG_SetPskServerCallback(testInfo.config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(testInfo.config, (HITLS_PskClientCb)ExampleClientCb); testInfo.client = FRAME_CreateLink(testInfo.config, testInfo.uioType); HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY); testInfo.server = FRAME_CreateLink(testInfo.config, testInfo.uioType); ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT), HITLS_MSG_HANDLE_HANDSHAKE_FAILURE); ALERT_Info info = {0}; ALERT_GetInfo(testInfo.client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC001 * @spec - * @title The supported_versions in the clientHello is extended to 0x0304 (TLS 1.3). If the server supports only 1.2, the * server returns a "protocol_version" warning and the handshake fails. * @precon nan * @brief Appendix D. Backward Compatibility line 247 * @expect * 1. The setting is successful. * 2. The setting is successful. * 3. The connection is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config_c = HITLS_CFG_NewTLS13Config(); config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->cipherSuites.data[0] = 0xC02F; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(serverTlsCtx->hsCtx->state, TRY_SEND_CERTIFICATE); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC004 * @spec - * @title clientHello version is 0x0303 and the server supports only 1.3. The server returns "protocol_version" and the * handshake fails. * @precon nan * @brief Appendix D. Backward Compatibility line 247 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC004() { FRAME_Init(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config_c = HITLS_CFG_NewTLS12Config(); config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC005 * @spec - * @titleSet that the server supports only TLS 1.2 and the client supports TLS 1.3. ClientHello legacy_version contains 0x0303 (TLS 1.2). The supported_versions field is extended to 0x0304 and 0x0303. The server responds with serverHello and ServerHello.version is 0x0303, The client agrees to use this version, and the handshake negotiation is successful. * @precon nan * @brief Appendix D. Backward Compatibility line 245 * @expect 1. The handshake negotiation is successful. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC005() { FRAME_Init(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config_c = HITLS_CFG_NewTLSConfig(); config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config_c, TLS12_VERSION_BIT|TLS13_VERSION_BIT) == HITLS_SUCCESS); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC006 * @spec - * @title: The server supports only TLS 1.2, and the client supports TLS 1.3. ClientHello legacy_version contains 0x0303 * (TLS 1.2). The supported_versions field is extended to 0x0304 and 0x0303. The server responds with * serverHello and ServerHello.version is 0x0303, The client agrees to use this version. The connection * establishment is interrupted, and the session is restored. The restoration is successful. * @precon nan * @brief Appendix D. Backward Compatibility line 245 * @expect 1. The handshake negotiation is successful. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC006() { FRAME_Init(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config_c = HITLS_CFG_NewTLSConfig(); config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config_c, TLS12_VERSION_BIT|TLS13_VERSION_BIT) == HITLS_SUCCESS); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = NULL; clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 1); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ static void Test_SERVERHELLO_VERSION(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS12; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.version.data = 0x0301; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC007 * @spec - * @titleSet that the server supports only TLS 1.2 and the client supports TLS 1.3. ClientHello legacy_version contains * 0x0303 (TLS 1.2), and supported_versions is extended to 0x0304, 0x0303, and 0x0301: The server responds with * serverHello. The value of ServerHello.version is 0x0303. The client agrees to use this version. The * connection establishment is interrupted and the session is restored, Before the client receives the * ServerHello message, the session fails to be resumed after Server.version is changed to 0x0301. * @precon nan * @brief Appendix D. Backward Compatibility line 245 * @expect 1. Failed to restore the session. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC007() { FRAME_Init(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config_c = HITLS_CFG_NewTLSConfig(); config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config_c, TLS12_VERSION_BIT | TLS13_VERSION_BIT) == HITLS_SUCCESS); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = NULL; clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); FRAME_FreeLink(server); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_SERVERHELLO_VERSION}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKTICKETLIFETIME_FUNC_TC001 * @spec - * @title Set the life cycle of ticket_lifetime to 10s. After the first connection is established, send the session using the * ticket through the client to resume, The server processes the message 10 seconds after receiving the ticket. The * server determines that the ticket has expired and the session fails to be restored. * @precon nan * @brief 4.6.1. New Session Ticket Message line 164 * @expect 1. Expected handshake failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_PSKTICKETLIFETIME_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetSessionTimeout(testInfo.config, 10); ASSERT_EQ(DoHandshake(&testInfo), HITLS_SUCCESS); testInfo.clientSession = HITLS_GetDupSession(testInfo.client->ssl); ASSERT_TRUE(testInfo.clientSession != NULL); FRAME_FreeLink(testInfo.client); testInfo.client = NULL; FRAME_FreeLink(testInfo.server); testInfo.server = NULL; HITLS_CFG_FreeConfig(testInfo.config); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, testInfo.clientSession), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); sleep(11); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(testInfo.clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CERT_SIGNATURE_FUNC_TC001 * @spec - * @title Certificate chain: ecdsa_secp256r1_sha256. If the signature algorithm is ecdsa_secp256r1_sha256, the certificate * and certificate chain are successfully verified. * @precon nan * @brief 9.1. Mandatory-to-Implement Cipher Suites line 229 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CERT_SIGNATURE_FUNC_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256, CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; ASSERT_TRUE(HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t))== HITLS_SUCCESS); FRAME_CertInfo certInfo = { "rsa_sha/ca-3072.der:rsa_sha/inter-3072.der", NULL, NULL, NULL, NULL, NULL,}; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CERT_SIGNATURE_FUNC_TC002 * @spec - * @title Certificate chain: ecdsa_secp256r1_sha256. If the signature algorithm is ecdsa_secp256r1_sha256, the * certificate and certificate chain are successfully verified. * @precon nan * @brief 9.1. Mandatory-to-Implement Cipher Suites line 229 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CERT_SIGNATURE_FUNC_TC002() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256 }; ASSERT_TRUE(HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t))== HITLS_SUCCESS); FRAME_CertInfo certInfo1 = { "rsa_pss_rsae/rsa_root.der:rsa_pss_rsae/rsa_intCa.der", NULL, NULL, NULL, NULL, NULL,}; FRAME_CertInfo certInfo2 = { "rsa_pss_rsae/rsa_root.der:rsa_pss_rsae/rsa_intCa.der", "rsa_pss_rsae/rsa_intCa.der", "rsa_pss_rsae/rsa_dev.der", NULL, "rsa_pss_rsae/rsa_dev.key.der", NULL,}; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo1); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo2); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CERT_SIGNATURE_FUNC_TC003 * @spec - * @title Certificate chain: ecdsa_secp256r1_sha256. If the signature algorithm is ecdsa_secp256r1_sha256, the * certificate and certificate chain are successfully verified. * @precon nan * @brief 9.1. Mandatory-to-Implement Cipher Suites line 229 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CERT_SIGNATURE_FUNC_TC003() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; ASSERT_TRUE(HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t))== HITLS_SUCCESS); FRAME_CertInfo certInfo = { "ecdsa/ca-nist521.der:ecdsa/inter-nist521.der", NULL, NULL, NULL, NULL, NULL,}; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECVERSION_FUNC_TC001 * @spec - * @title After the server negotiates the version number for the first time, the serverHello, Certificate, Server Key * Exchange, Certificate Request, Server Hello Done, Certificate, Certificate Key Exchange, The * legacy_record_version of all record messages, such as Certificate Verify, Change Cipher Spec, and Finished, * is the negotiated version. * @precon nan * @brief Appendix D. Backward Compatibility line 242 * @expect 1. The expected version number is the negotiated version. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECVERSION_FUNC_TC001(int flag, int type) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FrameUioUserData *ioUserData = NULL; config = HITLS_CFG_NewTLS12Config(); HITLS_CFG_SetClientVerifySupport(config, true); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, flag, type) == HITLS_SUCCESS); if (flag == 1) { HITLS_Connect(client->ssl); ioUserData = BSL_UIO_GetUserData(client->io); } else { HITLS_Accept(server->ssl); ioUserData = BSL_UIO_GetUserData(server->io); } uint8_t *recvBuf = ioUserData->sndMsg.msg; uint32_t recvLen = ioUserData->sndMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.recVersion.data, 0x0303); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECVERSION_FUNC_TC002 * @spec - * @title Renegotiation. After the server negotiates the version number, the serverHello, Certificate, Server Key * Exchange, Certificate Request, Server Hello Done, Certificate, Certificate Key Exchange, Certificate Verify, * Change Cipher Spec, Finished, and other record messages legacy_record_version indicates the renegotiation version. * @precon nan * @brief Appendix D. Backward Compatibility line 242 * @expect 1. The expected version number is the negotiated version. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECVERSION_FUNC_TC002(int flag, int type) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FrameUioUserData *ioUserData = NULL; config = HITLS_CFG_NewTLS12Config(); HITLS_CFG_SetClientVerifySupport(config, true); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_SetRenegotiationSupport(server->ssl, true); HITLS_SetRenegotiationSupport(client->ssl, true); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(server->ssl) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, flag, type), HITLS_SUCCESS); if (flag == 1) { HITLS_Connect(client->ssl); ioUserData = BSL_UIO_GetUserData(client->io); } else { HITLS_Accept(server->ssl); ioUserData = BSL_UIO_GetUserData(server->io); } uint8_t *recvBuf = ioUserData->sndMsg.msg; uint32_t recvLen = ioUserData->sndMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS12, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.recVersion.data, 0x0303); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_PARSE_CA_LIST_TC001 * @spec - * @title The CA list is parsed correctly. * @precon nan * @brief 1. Use the default configuration items to configure the client and server. stop the server in the TRY_RECV_CLIENT_HELLO * state. Expected result 1 is obtained. * 2. Get the client hello message from the server. Expected result 2 is obtained. * 3. Add the CA list to the client hello message. Expected result 3 is obtained. * 4. Reconnect the client. Expected result 4 is obtained. * @expect 1. The initialization is successful. * 2. The recvLen is not 0. * 3. The CA list is packed correctly. * 4. The client hello message is parsed correctly. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_PARSE_CA_LIST_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FrameUioUserData *ioUserData = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO), HITLS_SUCCESS); ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.handshakeType = CLIENT_HELLO; frameType.keyExType = HITLS_KEY_EXCH_ECDHE; ASSERT_TRUE(FRAME_ParseMsgHeader(&frameType, recvBuf, recvLen, &frameMsg, &recvLen) == HITLS_SUCCESS); uint8_t caList[] = {0x00, 0x06, 0x00, 0x04, 0x4a, 0x4b, 0x4c, 0x4d}; frameMsg.body.hsMsg.body.clientHello.caList.exState = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.caList.exType.data = HS_EX_TYPE_CERTIFICATE_AUTHORITIES; frameMsg.body.hsMsg.body.clientHello.caList.exType.state = ASSIGNED_FIELD; FRAME_ModifyMsgArray8(caList, sizeof(caList), &frameMsg.body.hsMsg.body.clientHello.caList.list, &frameMsg.body.hsMsg.body.clientHello.caList.listSize); frameMsg.body.hsMsg.body.clientHello.caList.exLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.caList.exLen.data = sizeof(caList) + sizeof(uint16_t); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); memset_s(&frameMsg, sizeof(frameMsg), 0, sizeof(frameMsg)); ASSERT_NE(FRAME_CreateConnection(server, client, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_extensions_2.c
C
unknown
50,229
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "hitls_error.h" #include "tls.h" #include "change_cipher_spec.h" #include "frame_tls.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "frame_link.h" #include "frame_io.h" #include "frame_msg.h" #include "simulate_io.h" #include "stub_replace.h" #include "hs.h" #include "alert.h" #include "bsl_sal.h" #include "securec.h" #include "app.h" #include "hs_kx.h" #include "hs_msg.h" #include "rec.h" #include "conn_init.h" #include "parse.h" #include "hs_common.h" #include "common_func.h" #include "hlt.h" #include "process.h" #include "hitls_crypt_init.h" #include "rec_wrapper.h" #define REC_TLS_RECORD_HEADER_LEN 5 #define ALERT_BODY_LEN 2u #define READ_BUF_SIZE 18432 #define ERROR_VERSION_BIT 0x00000000U #define READ_BUF_LEN_18K (18 * 1024) #define BUF_SIZE_DTO_TEST (18 * 1024) #define ROOT_DER "%s/ca.der:%s/inter.der" #define INTCA_DER "%s/inter.der" #define SERVER_DER "%s/server.der" #define SERVER_KEY_DER "%s/server.key.der" #define CLIENT_DER "%s/client.der" #define CLIENT_KEY_DER "%s/client.key.der" static char *g_serverName = "testServer"; uint32_t g_uiPort = 18890; /* END_HEADER */ int32_t RecParseInnerPlaintext(TLS_Ctx *ctx, uint8_t *text, uint32_t *textLen, uint8_t *recType); int32_t STUB_RecParseInnerPlaintext(TLS_Ctx *ctx, uint8_t *text, uint32_t *textLen, uint8_t *recType) { (void)ctx; (void)text; (void)textLen; *recType = (uint8_t)REC_TYPE_APP; return HITLS_SUCCESS; } void SetFrameType(FRAME_Type *frametype, uint16_t versionType, REC_Type recordType, HS_MsgType handshakeType, HITLS_KeyExchAlgo keyExType) { frametype->versionType = versionType; frametype->recordType = recordType; frametype->handshakeType = handshakeType; frametype->keyExType = keyExType; frametype->transportType = BSL_UIO_TCP; } void TestSetCertPath(HLT_Ctx_Config *ctxConfig, char *SignatureType) { if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA1", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA1")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA256")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, RSA_SHA256_PRIV_PATH3, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA384")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA384_EE_PATH, RSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA512", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA512")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA512_EE_PATH, RSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", strlen("CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA256_EE_PATH, ECDSA_SHA256_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", strlen("CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA384_EE_PATH, ECDSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", strlen("CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA512_EE_PATH, ECDSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SHA1", strlen("CERT_SIG_SCHEME_ECDSA_SHA1")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA1_CA_PATH, ECDSA_SHA1_CHAIN_PATH, ECDSA_SHA1_EE_PATH, ECDSA_SHA1_PRIV_PATH, "NULL", "NULL"); } } static int SetCertPath(HLT_Ctx_Config *ctxConfig, const char *certStr, bool isServer) { char caCertPath[50]; char chainCertPath[30]; char eeCertPath[30]; char privKeyPath[30]; int32_t ret = sprintf_s(caCertPath, sizeof(caCertPath), ROOT_DER, certStr, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(chainCertPath, sizeof(chainCertPath), INTCA_DER, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(eeCertPath, sizeof(eeCertPath), isServer ? SERVER_DER : CLIENT_DER, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(privKeyPath, sizeof(privKeyPath), isServer ? SERVER_KEY_DER : CLIENT_KEY_DER, certStr); ASSERT_TRUE(ret > 0); HLT_SetCaCertPath(ctxConfig, (char *)caCertPath); HLT_SetChainCertPath(ctxConfig, (char *)chainCertPath); HLT_SetEeCertPath(ctxConfig, (char *)eeCertPath); HLT_SetPrivKeyPath(ctxConfig, (char *)privKeyPath); return 0; EXIT: return -1; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVE_RENEGOTIATION_REQUEST_FUNC_TC001 * @spec Because TLS 1.3 forbids renegotiation, if a server has negotiated * TLS 1.3 and receives a ClientHello at any other time, it MUST * terminate the connection with an "unexpected_message" alert. * @title Initialize the client server to tls1.3. After the connection is established, the client sends a client hello message. * The expected server sends an alarm after receiving the message and disconnects the connection. * @precon nan * @brief 4.1.1. ryptographic Negotiation row15 * Initialize the client server to tls1.3. After the connection is established, the client sends a client hello * message. * The expected server sends an alarm after receiving the message and disconnects the connection. * @expect 1. The server sends an alarm and the connection is disconnected. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVE_RENEGOTIATION_REQUEST_FUNC_TC001() { FRAME_Init(); /* Initialize the client server to tls1.3. */ HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportRenegotiation = true; FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); /* After the connection is established, the client sends a client hello message. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); FrameMsg recMsg = {0}; FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg + REC_TLS_RECORD_HEADER_LEN, ioServerData->recMsg.len - REC_TLS_RECORD_HEADER_LEN) == EOK); recMsg.len = ioServerData->recMsg.len - 5; ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS13); ASSERT_TRUE(clientTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS13); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(REC_Write(clientTlsCtx, REC_TYPE_HANDSHAKE, recMsg.msg, recMsg.len), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyClientHello(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *userData) { (void)ctx; (void)userData; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->supportedVersion.exState = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_DOWN_GRADE_FUNC_TC001 * @spec random: 32 bytes generated by a secure random number generator. See * Appendix C for additional information. The last 8 bytes MUST be * overwritten as described below if negotiating TLS 1.2 or TLS 1.1, * but the remaining bytes MUST be random. This structure is * generated by the server and MUST be generated independently of the ClientHello.random. * @title Initialize the client and server to tls1.3. Delete the supportversion extension when sending clienthello * messages. * After receiving the message, the server negotiates with the TLS1.2 and returns the serverhello after the random * number is overwrritened. * After receiving the serverhello message, the client checks the random number and sends the ALERT_ELLEGAL_PARAMETER alarm. * @precon nan * @brief 4.1.3. Server Hello row24 * Initialize the client server to tls1.3 and delete the supportversion extension when sending client hello * messages. * After receiving the message, the server negotiates TLS1.2 and returns the serverhello after the random number is * overwrritened. * After receiving the serverhello message, the client checks the random number and sends the ALERT_LOCKGAL_PARAMETER a larm. * @expect 1. The client sends the ALERT_AIRGAL_PARAMETER alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_DOWN_GRADE_FUNC_TC001() { FRAME_Init(); /* Initialize the client and server to tls1.3. Delete the supportversion extension when sending clienthello * messages. */ HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, }; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(tlsConfig, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); HITLS_CFG_SetVersionSupport(tlsConfig, 0x00000030U); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyClientHello}; RegisterWrapper(wrapper); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); /* After receiving the message, the server negotiates with the TLS1.2 and returns the serverhello after the random * number is overwrritened. */ ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); /* After receiving the serverhello message, the client checks the random number and sends the * ALERT_ELLEGAL_PARAMETER alarm. */ ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC001 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title Client. The certificate is received after the clienthello message is sent. * @precon nan * @brief 4.Handshake Protocol row9 * Client, receiving the certificate after sending the clienthello message. * @expect 1. Return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = false; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FRAME_LinkObj *client2 = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server2 = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client2 != NULL); ASSERT_TRUE(server2 != NULL); HITLS_Ctx *clientTlsCtx2 = FRAME_GetTlsCtx(client2); HITLS_Ctx *serverTlsCtx2 = FRAME_GetTlsCtx(server2); ASSERT_TRUE(FRAME_CreateConnection(client2, server2, true, TRY_RECV_CERTIFICATE_REQUEST) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx2->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx2->state == CM_STATE_HANDSHAKING); char *buffer = BSL_SAL_Calloc(1u, MAX_RECORD_LENTH); FrameUioUserData *ioUserData2 = BSL_UIO_GetUserData(client2->io); uint8_t *recvBuf2 = ioUserData2->recMsg.msg; uint32_t recvLen2 = ioUserData2->recMsg.len; memcpy_s(buffer, MAX_RECORD_LENTH, recvBuf2, recvLen2); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->recMsg.len = 0; ASSERT_EQ(FRAME_TransportRecMsg(client->io, buffer, recvLen2), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); FRAME_FreeLink(client2); FRAME_FreeLink(server2); BSL_SAL_FREE(buffer); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC002 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title Client, unidirectional authentication, certificateverify received after receiving the serverhello message * @precon nan * @brief 4.Handshake Protocol row9 * Client, unidirectional authentication, certificateverify received after receiving the server hello message * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = false; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); client->ssl->hsCtx->state = TRY_RECV_ENCRYPTED_EXTENSIONS; ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC003 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title Client, two-way authentication, certificate received after receiving the serverhello message * @precon nan * @brief 4.Handshake Protocol row9 * Client, two-way authentication, certificate received after receiving the serverhello message * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); client->ssl->hsCtx->state = TRY_RECV_ENCRYPTED_EXTENSIONS; ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC004 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title Client, two-way authentication, receiving certificateverify after receiving certificaterequest * @precon nan * @brief 4.Handshake Protocol row9 * Client, two-way authentication, receiving certificateverify after receiving certificaterequest * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC004() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); client->ssl->hsCtx->state = TRY_RECV_CERTIFICATE; ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC005 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title Client, unidirectional authentication. After receiving the certificate, the client receives the finished message. * @precon nan * @brief 4.Handshake Protocol row9 * Client, unidirectional authentication. After receiving the certificate, the client receives the finished message. * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC005() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = false; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); client->ssl->hsCtx->state = TRY_RECV_CERTIFICATE_VERIFY; ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC006 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title Client, unidirectional authentication, receiving appdata after receiving certificateverify * @precon nan * @brief 4.Handshake Protocol row9 * Client, unidirectional authentication, receiving appdata after receiving certificateverify * @expect 1. Return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC006() { FRAME_Init(); STUB_Init(); FuncStubInfo tmpRpInfo = { 0 }; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = false; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); STUB_Replace(&tmpRpInfo, RecParseInnerPlaintext, STUB_RecParseInnerPlaintext); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&tmpRpInfo); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC007 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title Client, unidirectional authentication, certificateverify received after receiving encryptedextensions * @precon nan * @brief 4.Handshake Protocol row9 * Client, unidirectional authentication, certificateverify received after receiving encryptedextensions * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC007() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = false; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); client->ssl->hsCtx->state = TRY_RECV_CERTIFICATE_REQUEST; ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC008 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title The server receives the certificate message in idle state. * @precon nan * @brief 4.Handshake Protocol row9 * The server receives a certificate message in idle state. * @expect 1. Return HITLS_CM_LINK_UNESTABLICED @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC008() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FRAME_LinkObj *client2 = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server2 = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client2 != NULL); ASSERT_TRUE(server2 != NULL); HITLS_Ctx *clientTlsCtx2 = FRAME_GetTlsCtx(client2); HITLS_Ctx *serverTlsCtx2 = FRAME_GetTlsCtx(server2); ASSERT_TRUE(FRAME_CreateConnection(client2, server2, false, TRY_RECV_CERTIFICATE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx2->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx2->state == CM_STATE_HANDSHAKING); char *buffer = BSL_SAL_Calloc(1u, MAX_RECORD_LENTH); FrameUioUserData *ioUserData2 = BSL_UIO_GetUserData(server2->io); uint8_t *recvBuf2 = ioUserData2->recMsg.msg; uint32_t recvLen2 = ioUserData2->recMsg.len; memcpy_s(buffer, MAX_RECORD_LENTH, recvBuf2, recvLen2); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); ioUserData->recMsg.len = 0; ASSERT_EQ(FRAME_TransportRecMsg(server->io, buffer, recvLen2), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_CM_LINK_UNESTABLISHED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); FRAME_FreeLink(client2); FRAME_FreeLink(server2); BSL_SAL_FREE(buffer); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC009 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title The server uses unidirectional authentication. The certificate message is received after the client hello message is received. * @precon nan * @brief 4.Handshake Protocol row9 * Server, unidirectional authentication, certificate message received after receiving client hello messages. * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC009() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CERTIFICATE) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); server->ssl->hsCtx->state = TRY_RECV_FINISH; ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC010 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title server, unidirectional authentication, receiving the app message after receiving the client hello message * @precon nan * @brief 4.Handshake Protocol row9 * Server, unidirectional authentication, receiving the app message after receiving the client hello message * @expect 1. Return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC010() { FRAME_Init(); STUB_Init(); FuncStubInfo tmpRpInfo = { 0 }; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = false; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); STUB_Replace(&tmpRpInfo, RecParseInnerPlaintext, STUB_RecParseInnerPlaintext); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&tmpRpInfo); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC011 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title server, two-way authentication, certificateverify message received after client hello is received * @precon nan * @brief 4.Handshake Protocol row9 * The server, two-way authentication, receives the certificateverify message after receiving the client hello * message. * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC011() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); server->ssl->hsCtx->state = TRY_RECV_CERTIFICATE; ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC012 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title server, two-way authentication, receiving the finish message after receiving the certificate message * @precon nan * @brief 4.Handshake Protocol row9 * The server, two-way authentication, receives the finish message after receiving the certificate message. * @expect 1. Return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC012() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = false; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); server->ssl->hsCtx->state = TRY_RECV_CERTIFICATE_VERIFY; ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC013 * @spec Protocol messages MUST be sent in the order defined in Section 4.4.1 * and shown in the diagrams in Section 2. A peer which receives a * handshake message in an unexpected order MUST abort the handshake * with an "unexpected_message" alert. * @title server, two-way authentication, receiving the app message after receiving the certificateverify message * @precon nan * @brief 4.Handshake Protocol row9 * The server, two-way authentication, receives the app message after receiving the certificateverify message. * @expect 1. Return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_UNEXPECTMSG_FUNC_TC013() { FRAME_Init(); STUB_Init(); FuncStubInfo tmpRpInfo = { 0 }; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); STUB_Replace(&tmpRpInfo, RecParseInnerPlaintext, STUB_RecParseInnerPlaintext); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&tmpRpInfo); } /* END_CASE */ static void Test_ModifyClientHelloNullKeyshare(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *userData) { (void)ctx; (void)userData; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->keyshares.exLen.data = 2; clientMsg->keyshares.exKeyShareLen.data = 0; clientMsg->keyshares.exKeyShares.state = MISSING_FIELD; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_NULL_KEYSHARE_FUNC_TC001 * @spec If the server selects an (EC)DHE group and the client did not offer a * compatible "key_share" extension in the initial ClientHello, the * server MUST respond with a HelloRetryRequest (Section 4.1.4) message. * @title Construct the clienthello message sent by the client. The key_share extension is empty and the psk extension is not carried. The server is expected to send a hellorequest message. * @precon nan * @brief 4.Handshake Protocol row9 * Construct the client hello message sent by the client. The key_share extension is empty and the psk extension is not carried. The server is expected to send a hellorequest message. * @expect 1. The server sends hrr and waits for receiving the second client hello. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_NULL_KEYSHARE_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyClientHelloNullKeyshare}; RegisterWrapper(wrapper); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ClearWrapper(); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SECOND_GROUP_SUPPORT_FUNC_TC001 * @spec When a client first connects to a server, it is REQUIRED to send the * ClientHello as its first TLS message. The client will also send a * ClientHello when the server has responded to its ClientHello with a * HelloRetryRequest. In that case, the client MUST send the same * ClientHello without modification, except as follows: * @title 1. Set the client server to tls1.3. Set the first group server not to support the client, but the second group * server to support the client, * The server is expected to send a helloretryrequest message. The client hello message is sent after the client * hello message is updated. The group in the keyshare of the client hello message is changed. The connection is * expected to be successfully set up. * @precon nan * @brief 4.1.2. Client Hello row14 * 1. Set the client server to tls1.3. Set the first group server to not support the client server, and set the * second group server to support the client server. * The server is expected to send a helloretryrequest message. The client hello message is sent after the client * hello message is updated. The group in the keyshare of the client hello message is changed. The connection is * expected to be successfully established. * @expect 1. The server sends hrr and the connection is successfully established. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SECOND_GROUP_SUPPORT_FUNC_TC001() { FRAME_Init(); /* Set the client server to tls1.3. Set the first group server not to support the client, but the second group * server to support the client */ HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SECOND_GROUP_SUPPORT_FUNC_TC002 * @spec When a client first connects to a server, it is REQUIRED to send the * ClientHello as its first TLS message. The client will also send a * ClientHello when the server has responded to its ClientHello with a * HelloRetryRequest. In that case, the client MUST send the same * ClientHello without modification, except as follows: * @title 1. Set the client server to tls1.3. Set the first group server not to support the client, but the second group * server to support the client, * The server is expected to send a helloretryrequest message, construct the same client hello message sent by the * client, and the server is expected to reject connection establishment. * @precon nan * @brief 4.1.2. Client Hello row14 * 1. Set the client server to tls1.3. Set the first group server not to support the client, and the second group * server to support the client. * The server is expected to send a helloretryrequest message, construct the same client hello message sent by the * client, and the server is expected to reject connection establishment. * @expect 1. Link establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SECOND_GROUP_SUPPORT_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); char *buffer = BSL_SAL_Calloc(1u, MAX_RECORD_LENTH); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; memcpy_s(buffer, MAX_RECORD_LENTH, recvBuf, recvLen); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, recvBuf, recvLen) == HITLS_SUCCESS); ioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_INVALID_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); BSL_SAL_FREE(buffer); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SECOND_GROUP_SUPPORT_FUNC_TC003 * @spec When a client first connects to a server, it is REQUIRED to send the * ClientHello as its first TLS message. The client will also send a * ClientHello when the server has responded to its ClientHello with a * HelloRetryRequest. In that case, the client MUST send the same * ClientHello without modification, except as follows: * @titleSet the client server to tls1.3, and set the first group server not to support the client, and the second group * server to support the client, * The hash of the cipher suite on the server does not match the hash corresponding to the psk set on the * client. The server is expected to send a helloretryrequest message, * The client resends the client hello message and removes the psk extension. * @precon nan * @brief 4.1.2. Client Hello row14 * Set the client server to tls1.3. Set the first group server not to support the client, but the second group * server to support the client, * The hash of the cipher suite on the server does not match the hash corresponding to the psk set on the * client. The server is expected to send a helloretryrequest message, * The client resends the client hello message and removes the psk extension. * @expect 1. The second clienthello does not contain the psk. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SECOND_GROUP_SUPPORT_FUNC_TC003() { FRAME_Init(); HITLS_Session *Session = {0}; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); Session = HITLS_GetDupSession(client->ssl); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(HITLS_SetSession(client->ssl, Session) == HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_TRUE(clientMsg->psks.exState == INITIAL_FIELD); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ioUserData = BSL_UIO_GetUserData(client->io); recvBuf = ioUserData->recMsg.msg; recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->cipherSuite.data = HITLS_AES_128_GCM_SHA256; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ioUserData = BSL_UIO_GetUserData(server->io); recvBuf = ioUserData->recMsg.msg; recvLen = ioUserData->recMsg.len; parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_TRUE(clientMsg->psks.exState == MISSING_FIELD); FRAME_CleanMsg(&frameType, &frameMsg); EXIT: HITLS_SESS_Free(Session); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RENEGOTIATION_OLD_VERSION_FUNC_TC001 * @spec If a server established a TLS connection with a previous version of * TLS and receives a TLS 1.3 ClientHello in a renegotiation, it MUST * retain the previous protocol version. In particular, it MUST NOT * negotiate TLS 1.3. * @title 1. On the server end of 1.3, after the connection between 1.2 and 1.2 is successfully established, initiate renegotiation and change the client version to 1.3. The supported version includes tls1.2. The expected version is tls1.2. * @precon nan * @brief 4.1.1. Cryptographic Negotiation row16 * 1. On the 1.3 server, after the 1.2 connection is successfully established, initiate renegotiation and change the client version to 1.3. The supported version includes tls1.2. The tls1.2 version is expected to be negotiated. * @expect 1. The TLS1.2 version is expected to be negotiated. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RENEGOTIATION_OLD_VERSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLS13Config(); tlsConfig_s->isSupportClientVerify = true; tlsConfig_s->isSupportRenegotiation = true; HITLS_CFG_SetKeyExchMode(tlsConfig_s, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_s, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(tlsConfig_s, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_s != NULL); HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLSConfig(); HITLS_CFG_SetVersionSupport(tlsConfig_c, 0x00000010U); tlsConfig_c->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_c != NULL); tlsConfig_c->isSupportRenegotiation = true; FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); HITLS_SetClientRenegotiateSupport(server->ssl, true); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); ASSERT_TRUE(clientTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); HITLS_CFG_SetVersionSupport(&(clientTlsCtx->config.tlsConfig), 0x00000030U); ASSERT_EQ(HITLS_Renegotiate(clientTlsCtx), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_RENEGOTIATION); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); EXIT: HITLS_CFG_FreeConfig(tlsConfig_s); HITLS_CFG_FreeConfig(tlsConfig_c); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RENEGOTIATION_OLD_VERSION_FUNC_TC002 * @spec If a server established a TLS connection with a previous version of * TLS and receives a TLS 1.3 ClientHello in a renegotiation, it MUST * retain the previous protocol version. In particular, it MUST NOT * negotiate TLS 1.3. * @title 1. On the server end of 1.2, after the connection is successfully established, the client version is changed to 1.3 * and the minimum supported version is tls1.3. The renegotiation fails. * @precon nan * @brief 4.1.1. Cryptographic Negotiation row16 * 1. After the connection between the client and the client is set up successfully, the client version is changed * to 1.3 and the minimum supported version is tls1.3. The renegotiation fails. * @expect 1. Expected renegotiation failure @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RENEGOTIATION_OLD_VERSION_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLS13Config(); tlsConfig_s->isSupportClientVerify = true; tlsConfig_s->isSupportRenegotiation = true; HITLS_CFG_SetKeyExchMode(tlsConfig_s, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_s, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE(HITLS_CFG_SetCipherSuites(tlsConfig_s, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_s != NULL); HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLS12Config(); tlsConfig_c->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_c != NULL); tlsConfig_c->isSupportRenegotiation = true; FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); HITLS_SetClientRenegotiateSupport(server->ssl, true); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); ASSERT_TRUE(clientTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); ASSERT_EQ(HITLS_Renegotiate(clientTlsCtx), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_RENEGOTIATION); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); HITLS_CFG_SetVersionSupport(&(clientTlsCtx->config.tlsConfig), 0x00000020U); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig_s); HITLS_CFG_FreeConfig(tlsConfig_c); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_VERSION_FUNC_TC001 * @spec In TLS 1.3, the client indicates its version preferences in the * "supported_versions" extension (Section 4.2.1) and the * legacy_version field MUST be set to 0x0303, which is the version * number for TLS 1.2. TLS 1.3 ClientHellos are identified as having a legacy_version of 0x0303 and a * supported_versions extension * present with 0x0304 as the highest version indicated therein. * @title The client server is initialized to the tls1.3 version, and the legacy_version in the sent clienthello * message is changed to 0x0302. The server is expected to return an alert. * @precon nan * @brief 4.1.2. Client Hello row17 * The client server is initialized to the tls1.3 version, and the legacy_version in the sent clienthello message * is changed to 0x0302. The server is expected to return an alert. * @expect 1. The server sends an alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_VERSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; /* The client server is initialized to the tls1.3 version, and the legacy_version in the sent clienthello * message is changed to 0x0302 */ clientMsg->version.data = 0x0302; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_VERSION_FUNC_TC002 * @spec In TLS 1.3, the client indicates its version preferences in the * "supported_versions" extension (Section 4.2.1) and the * legacy_version field MUST be set to 0x0303, which is the version * number for TLS 1.2. TLS 1.3 ClientHellos are identified as having a legacy_version of 0x0303 and a * supported_versions extension present with 0x0304 as the highest version indicated therein. * @title The client server is initialized to the tls1.3 version, and the legacy_version in the sent clienthello * message is changed to 0x0304. The server is expected to return an alert. * @precon nan * @brief 4.1.2. Client Hello row17 * The client server is initialized to the tls1.3 version, and the legacy_version in the sent clienthello message * is changed to 0x0304. The server is expected to return an alert. * @expect 1. The server sends an alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_VERSION_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; /* The client server is initialized to the tls1.3 version, and the legacy_version in the sent clienthello * message is changed to 0x0304. */ clientMsg->version.data = 0x0304; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC001 * @spec A client which has a cached session ID set by a pre-TLS 1.3 server SHOULD set this field to that value. * In compatibility mode (see Appendix D.4),this field MUST be non-empty, so a client not offering a * pre-TLS 1.3 session MUST generate a new 32-byte value. This value need not be random but SHOULD be unpredictable to avoid * implementations fixating on a specific value (also known as * ossification). Otherwise, it MUST be set as a zero-length vector * (i.e., a zero-valued single byte length field). * @title Set the client server to tls1.3 and check the legacy_session_id of the sent clienthello message. The value is a 32-byte value. * @precon nan * @brief 4.1.2. Client Hello row18 * Set the client server to tls1.3 and check the legacy_session_id of the sent clienthello to a 32-byte value. * @expect 1. Check the session ID. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Set the client server to tls1.3 and check the legacy_session_id of the sent clienthello message. The value * is a 32-byte value. */ FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_EQ(clientMsg->sessionIdSize.data, 32); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyClientHello_Sessionid_002(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *userData) { (void)ctx; (void)userData; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->sessionIdSize.data = 0; clientMsg->sessionId.size = 0; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /* @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC002 * @spec A client which has a cached session ID set by a pre-TLS 1.3 server SHOULD set this field to that value. * In compatibility mode (see Appendix D.4),this field MUST be non-empty, so a client not offering a * pre-TLS 1.3 session MUST generate a new 32-byte value. This value need not be random but SHOULD be unpredictable to avoid implementations fixating on a specific value (also known as * ossification). Otherwise, it MUST be set as a zero-length vector * (i.e., a zero-valued single byte length field). * @title Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to a single byte 0. The expected connection establishment is successful. * @precon nan * @brief 4.1.2. Client Hello row18 * Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to a single byte 0. The expected connection establishment is successful. * @expect 1. The connection is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); /* Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message * to a single byte 0 */ RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyClientHello_Sessionid_002}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO), HITLS_SUCCESS); clientTlsCtx->hsCtx->sessionIdSize = 0; ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC003 * @spec A client which has a cached session ID set by a pre-TLS 1.3 server SHOULD set this field to that value. * In compatibility mode (see Appendix D.4),this field MUST be non-empty, so a client not offering a * pre-TLS 1.3 session MUST generate a new 32-byte value. This value need not be random but SHOULD be * unpredictable to avoid implementations fixating on a specific value (also known as * ossification). Otherwise, it MUST be set as a zero-length vector * (i.e., a zero-valued single byte length field). * @title Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to * 2-byte 0. The expected connection establishment failure * @precon nan * @brief 4.1.2. Client Hello row18 * Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to * two bytes 0. The expected connection establishment fails. * @expect 1. Link establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->sessionIdSize.data = 0; /* Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to * 2-byte 0. */ clientMsg->sessionId.size = 2; clientMsg->sessionId.data[0] = 0x00; clientMsg->sessionId.data[1] = 0x00; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_PARSE_INVALID_MSG_LEN); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC004 * @spec A client which has a cached session ID set by a pre-TLS 1.3 server SHOULD set this field to that value. * In compatibility mode (see Appendix D.4),this field MUST be non-empty, so a client not offering a * pre-TLS 1.3 session MUST generate a new 32-byte value. This value need not be random but SHOULD be unpredictable to avoid implementations fixating on a specific value (also known as ossification). Otherwise, it MUST be set as a zero-length vector * (i.e., a zero-valued single byte length field). * @title Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to 1 byte 1. The expected connection establishment fails. * @precon nan * @brief 4.1.2. Client Hello row18 * Set the client server to tls1.3 and construct the value of legacy_session_id in the clienthello message to 1 byte 1. The expected connection establishment fails. * @expect 1. Connect establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC004() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; /* Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to * 1 byte 1. */ clientMsg->sessionIdSize.data = 1; clientMsg->sessionId.size = 1; clientMsg->sessionId.data[0] = 0x01; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_PARSE_INVALID_MSG_LEN); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyClientHello_Sessionid_005(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *userData) { (void)ctx; (void)userData; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->sessionIdSize.data = 26; clientMsg->sessionId.size = 26; const uint8_t sessionId_temp[26] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; ASSERT_TRUE(memcpy_s(clientMsg->sessionId.data, sizeof(sessionId_temp) / sizeof(uint8_t), sessionId_temp, sizeof(sessionId_temp) / sizeof(uint8_t)) == 0); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC005 * @spec A client which has a cached session ID set by a pre-TLS 1.3 server SHOULD set this field to that value. * In compatibility mode (see Appendix D.4),this field MUST be non-empty, so a client not offering a * pre-TLS 1.3 session MUST generate a new 32-byte value. This value need not be random but SHOULD be unpredictable to avoid implementations fixating on a specific value (also known as ossification). Otherwise, it MUST be set as a zero-length vector (i.e., a zero-valued single byte length field). * @title Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to 26 bytes 0. The expected connection is successfully established.. * @precon nan * @brief 4.1.2. Client Hello row18 * Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to 26 bytes 0. The expected link establishment success. * @expect 1. Link establishment success. * @expect 1. Link establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SESSION_ID_FUNC_TC005() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); /* Set the client server to tls1.3 and construct the value of legacy_session_id in the sent clienthello message to * 26 bytes 0. */ RecWrapper wrapper = {TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyClientHello_Sessionid_005}; RegisterWrapper(wrapper); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CH_CIPHERSUITES_FUNC_TC001 * @spec cipher_suites: A list of the symmetric cipher options supported by * the client, specifically the record protection algorithm * (including secret key length) and a hash to be used with HKDF, in * descending order of client preference. Values are defined in * Appendix B.4. If the list contains cipher suites that the server * does not recognize, support, or wish to use, the server MUST * ignore those cipher suites and process the remaining ones as * usual. If the client is attempting a PSK key establishment, it SHOULD advertise at least one cipher suite * indicating a Hash associated with the PSK. * @title clienthello The first three cipher suites are abnormal values, tls1.2 cipher suites, and tls1.3 cipher suites * that are not configured on the server, The fourth cipher suite is supported by the server. It is expected that * the server selects the fourth cipher suite to establish a connection. * @precon nan * @brief 4.1.2. Client Hello row19 * The first three cipher suites of client hello are abnormal values, tls1.2 cipher suites, and tls1.3 cipher * suites that are not configured on the server, * The fourth cipher suite is supported by the server. It is expected that the server selects the fourth cipher * suite to establish a connection. * @expect 1. The connection is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CH_CIPHERSUITES_FUNC_TC001() { FRAME_Init(); HITLS_Config *config_c = HITLS_CFG_NewTLS13Config(); HITLS_Config *config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); config_c->isSupportClientVerify = true; config_s->isSupportClientVerify = true; /* clienthello The first three cipher suites are abnormal values, tls1.2 cipher suites, and tls1.3 cipher suites * that are not configured on the server, The fourth cipher suite is supported by the server. */ uint16_t cipherSuits_c[] = { 0x0041, HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256, HITLS_CHACHA20_POLY1305_SHA256, HITLS_AES_256_GCM_SHA384}; HITLS_CFG_SetCipherSuites(config_c, cipherSuits_c, sizeof(cipherSuits_c) / sizeof(uint16_t)); uint16_t cipherSuits_s[] = {HITLS_AES_256_GCM_SHA384}; HITLS_CFG_SetCipherSuites(config_s, cipherSuits_s, sizeof(cipherSuits_s) / sizeof(uint16_t)); FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_TRUE(server->ssl->negotiatedInfo.cipherSuiteInfo.cipherSuite == HITLS_AES_256_GCM_SHA384); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CH_CIPHERSUITES_FUNC_TC002 * @spec cipher_suites: A list of the symmetric cipher options supported by * the client, specifically the record protection algorithm * (including secret key length) and a hash to be used with HKDF, in * descending order of client preference. Values are defined in * Appendix B.4. If the list contains cipher suites that the server * does not recognize, support, or wish to use, the server MUST * ignore those cipher suites and process the remaining ones as * usual. If the client is attempting a PSK key establishment, it SHOULD advertise at least one cipher suite * indicating a Hash associated with the PSK. * @title The hash of the configured psk does not match the specified cipher suite when tls1.3 is set on the client * server. The expected psk does not exist in the client hello. * @precon nan * @brief 4.1.2. Client Hello row19 * When tls1.3 is set on the client and server, the hash of the psk does not match the specified cipher suite. It * is expected that the psk does not exist in the client hello. * @expect 1. No psk is expected in the clienthello. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CH_CIPHERSUITES_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); HITLS_CFG_SetPskServerCallback(tlsConfig, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(tlsConfig, (HITLS_PskClientCb)ExampleClientCb); /* The hash of the configured psk does not match the specified cipher suite when tls1.3 is set on the client * server. */ uint16_t cipherSuite = HITLS_AES_256_GCM_SHA384; HITLS_CFG_SetCipherSuites(tlsConfig, &cipherSuite, 1); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; ASSERT_TRUE(clientMsg->psks.exState == MISSING_FIELD); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_COMPRESSION_METHOD_FUNC_TC001 * @spec legacy_compression_methods: Versions of TLS before 1.3 supported * compression with the list of supported compression methods being * sent in this field. For every TLS 1.3 ClientHello, this vector * MUST contain exactly one byte, set to zero, which corresponds to * the "null" compression method in prior versions of TLS. If a * TLS 1.3 ClientHello is received with any other value in this * field, the server MUST abort the handshake with an * "illegal_parameter" alert. Note that TLS 1.3 servers might * receive TLS 1.2 or prior ClientHellos which contain other * compression methods and (if negotiating such a prior version) MUST follow the procedures for the appropriate * prior version of TLS. * @title Construct clienthello compression algorithm. The value is 0. The server is expected to return a decode * error alert. * @precon nan * @brief 4.1.2. Client Hello row20 * Construct the clienthello compression algorithm with a two-byte value and the value 0. The server is * expected to return a decode error alert. * @expect 1. Return the decode error alert. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_COMPRESSION_METHOD_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); /* Construct clienthello compression algorithm. The value is 0. */ FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->compressionMethodsLen.data = 2; clientMsg->compressionMethods.data = realloc(clientMsg->compressionMethods.data, 2 * sizeof(uint8_t)); clientMsg->compressionMethods.size = 2; clientMsg->compressionMethods.data[0] = 0x00; clientMsg->compressionMethods.data[1] = 0x00; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_COMPRESSION_METHOD_FUNC_TC002 * @spec legacy_compression_methods: Versions of TLS before 1.3 supported * compression with the list of supported compression methods being * sent in this field. For every TLS 1.3 ClientHello, this vector * MUST contain exactly one byte, set to zero, which corresponds to * the "null" compression method in prior versions of TLS. If a * TLS 1.3 ClientHello is received with any other value in this * field, the server MUST abort the handshake with an * "illegal_parameter" alert. Note that TLS 1.3 servers might * receive TLS 1.2 or prior ClientHellos which contain other * compression methods and (if negotiating such a prior version) MUST follow the procedures for the appropriate * prior version of TLS. * @title Constructs clienthello compression algorithm. The value is 1, indicating that the server returns * illegal_parameter alert. * @precon nan * @brief 4.1.2. Client Hello row20 * Construct the clienthello compression algorithm with a bit of one byte and the value is 1. The server is * expected to return illegal_parameter alert. * @expect 1. Return ALERT_ELLEGAL_PARAMETER @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_COMPRESSION_METHOD_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; /* Construct the clienthello compression algorithm with a bit of one byte and the value is 1. */ clientMsg->compressionMethodsLen.data = 1; clientMsg->compressionMethods.size = 1; clientMsg->compressionMethods.data[0] = 0x01; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_INVALID_COMPRESSION_METHOD); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_COMPRESSION_METHOD_FUNC_TC003 * @spec legacy_compression_methods: Versions of TLS before 1.3 supported * compression with the list of supported compression methods being * sent in this field. For every TLS 1.3 ClientHello, this vector * MUST contain exactly one byte, set to zero, which corresponds to * the "null" compression method in prior versions of TLS. If a * TLS 1.3 ClientHello is received with any other value in this * field, the server MUST abort the handshake with an * "illegal_parameter" alert. Note that TLS 1.3 servers might * receive TLS 1.2 or prior ClientHellos which contain other * compression methods and (if negotiating such a prior version) MUST follow the procedures for the appropriate * prior version of TLS. * @title Construct that the client version is TLS1.2 and the server version is TLS1.3. It is expected that the connection * can be set up normally. * @precon nan * @brief 4.1.2. Client Hello row20 * Construct the scenario where the client version is TLS1.2 and the server version is TLS1.3 and the expected * connection establishment is normal. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_COMPRESSION_METHOD_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLS13Config(); tlsConfig_s->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig_s, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_s, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE(HITLS_CFG_SetCipherSuites(tlsConfig_s, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_s != NULL); HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLS12Config(); tlsConfig_c->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_c != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); ASSERT_TRUE(clientTlsCtx->negotiatedInfo.version == HITLS_VERSION_TLS12); EXIT: HITLS_CFG_FreeConfig(tlsConfig_s); HITLS_CFG_FreeConfig(tlsConfig_c); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_UNKNOWN_EXTENSION_FUNC_TC001 * @spec extensions: Clients request extended functionality from servers by * sending data in the extensions field. The actual "Extension" * format is defined in Section 4.2. In TLS 1.3, the use of certain extensions is mandatory, as functionality has * moved into extensions to preserve ClientHello compatibility with previous * versions of TLS. Servers MUST ignore unrecognized extensions * @title Set the client server to tls1.3, construct a client hello message that carries the sni extension, and change * the sni extension type to 55 (unknown extension). It is expected that the server can establish a connection normally. * @precon nan * @brief 4.1.2. Client Hello row21 * Set the client server to tls1.3, construct a client hello message that carries the SNI extension, and change the * SNI extension type to 55 (unknown extension). The server is expected to establish a connection normally. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_UNKNOWN_EXTENSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetServerName(tlsConfig, (uint8_t *)g_serverName, (uint32_t)strlen(g_serverName)); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = {0}; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; /** Set the client server to tls1.3, construct a client hello message that carries the sni extension, and change * the sni extension type to 55 (unknown extension). */ clientMsg->serverName.exType.data = 55; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(clientTlsCtx->hsCtx->state, TRY_RECV_ENCRYPTED_EXTENSIONS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC001 * @spec TLS 1.3 servers will need to perform this check first and * only attempt to negotiate TLS 1.3 if the "supported_versions" * extension is present. If negotiating a version of TLS prior to 1.3, * a server MUST check that the message either contains no data after * legacy_compression_methods or that it contains a valid extensions * block with no data following. If not, then it MUST abort the * handshake with a "decode_error" alert. * @title: Set tls1.2 on the client and tls1.3 on the server. Construct the clienthello compression algorithm without * any extension. It is expected that the server can establish a connection. * @precon nan * @brief 4.1.2. Client Hello row22 * Set TLS 1.2 on the client and TLS 1.3 on the server. Construct the clienthello compression algorithm without * any extension. It is expected that the server can establish a connection. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLSConfig(); tlsConfig_s->isSupportExtendMasterSecret = false; tlsConfig_s->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig_s, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_s, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_CCM, HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, }; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(tlsConfig_s, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_s != NULL); /* Set tls1.2 on the client and tls1.3 on the server. Construct the clienthello compression algorithm without * any extension. */ HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLS12Config(); tlsConfig_c->isSupportExtendMasterSecret = false; tlsConfig_c->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_c != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->extensionState = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(tlsConfig_c); HITLS_CFG_FreeConfig(tlsConfig_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC002 * @spec TLS 1.3 servers will need to perform this check first and * only attempt to negotiate TLS 1.3 if the "supported_versions" * extension is present. If negotiating a version of TLS prior to 1.3, * a server MUST check that the message either contains no data after * legacy_compression_methods or that it contains a valid extensions * block with no data following. If not, then it MUST abort the * handshake with a "decode_error" alert. * @title: Set the client TLS 1.2 and server TLS 1.3. Construct the clienthello compression algorithm and carry the * extension and 3-byte data after the extension. The expected connection establishment fails and the decode_error * alert is returned. * @precon nan * @brief 4.1.2. Client Hello row22 * Set TLS 1.2 on the client and TLS 1.3 on the server. Construct the compression algorithm of the clienthello * message and carry the extension. After the extension, carry the 3-byte data. In this case, the connection * establishment fails and the decode_error alert is returned. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLSConfig(); tlsConfig_s->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig_s, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_s, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(tlsConfig_s, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_s != NULL); HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLSConfig(); HITLS_CFG_SetVersionSupport(tlsConfig_c, 0x00000010U); tlsConfig_c->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_c != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint32_t *recvLen = &ioUserData->recMsg.len; uint8_t *recvBuf = ioUserData->recMsg.msg; ASSERT_TRUE(recvLen != 0); recvBuf[4] += 3; recvBuf[8] += 3; recvBuf[*recvLen] = 0x01; recvBuf[(*recvLen)+1] = 0x01; recvBuf[(*recvLen)+2] = 0x01; *recvLen += 3; CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: HITLS_CFG_FreeConfig(tlsConfig_c); HITLS_CFG_FreeConfig(tlsConfig_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC003 * @spec TLS 1.3 servers will need to perform this check first and * only attempt to negotiate TLS 1.3 if the "supported_versions" * extension is present. If negotiating a version of TLS prior to 1.3, * a server MUST check that the message either contains no data after * legacy_compression_methods or that it contains a valid extensions * block with no data following. If not, then it MUST abort the * handshake with a "decode_error" alert. * @title: Set the client TLS 1.2 and server TLS 1.3. Construct the clienthello compression algorithm and carry 3-byte * data without extension. Expected connection establishment failure and return decode_error alert. * @precon nan * @brief 4.1.2. Client Hello row22 * Set TLS 1.2 on the client and TLS 1.3 on the server. Construct the compression algorithm of the clienthello * message without extension and carry 3-byte data. Expectedly, connection establishment fails and decode_error * alert is returned. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLS13Config(); tlsConfig_s->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig_s, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_s, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE(HITLS_CFG_SetCipherSuites(tlsConfig_s, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_s != NULL); HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLS12Config(); tlsConfig_c->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_c != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->extensionState = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); /* Set the client TLS 1.2 and server TLS 1.3. Construct the clienthello compression algorithm and carry 3-byte * data without extension. */ sendBuf[4] += 3; sendBuf[8] += 3; sendBuf[sendLen] = 0x01; sendBuf[sendLen + 1] = 0x01; sendBuf[sendLen + 2] = 0x01; sendLen += 3; ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: HITLS_CFG_FreeConfig(tlsConfig_c); HITLS_CFG_FreeConfig(tlsConfig_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC004 * @spec TLS 1.3 servers will need to perform this check first and * only attempt to negotiate TLS 1.3 if the "supported_versions" * extension is present. If negotiating a version of TLS prior to 1.3, * a server MUST check that the message either contains no data after * legacy_compression_methods or that it contains a valid extensions * block with no data following. If not, then it MUST abort the * handshake with a "decode_error" alert. * @title 4. Set tls1.2 on the client and tls1.3 on the server. Construct the clienthello message that carries the SNI * extension. The SNI length is too large and does not match the content. As a result, the expected connection * establishment fails and a decode_error alert message is returned. * @precon nan * @brief 4.1.2. Client Hello row22 * 4. Set tls1.2 on the client and tls1.3 on the server. Construct a clienthello message that carries the SNI * extension. The SNI length is too large and does not match the content. As a result, the expected connection * establishment fails and a decode_error alert message is returned. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_DATA_AFTER_COMPRESSION_FUNC_TC004() { FRAME_Init(); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLS13Config(); tlsConfig_s->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig_s, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_s, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(tlsConfig_s, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_s != NULL); HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLS12Config(); HITLS_CFG_SetServerName(tlsConfig_c, (uint8_t *)g_serverName, (uint32_t)strlen(g_serverName)); tlsConfig_c->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_c != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->serverName.exDataLen.data += 1; /* Set tls1.2 on the client and tls1.3 on the server. Construct the clienthello message that carries the SNI * extension. */ uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_PARSE_INVALID_MSG_LEN); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_DECODE_ERROR); EXIT: HITLS_CFG_FreeConfig(tlsConfig_c); HITLS_CFG_FreeConfig(tlsConfig_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_LEGACY_VERSION_FUNC_TC001 * @spec legacy_version: In previous versions of TLS, this field was used for version negotiation and represented the * selected version number * for the connection. In TLS 1.3, the TLS server indicates * its version using the "supported_versions" extension * (Section 4.2.1), and the legacy_version field MUST be set to * 0x0303, which is the version number for TLS 1.2. (See Appendix D * for details about backward compatibility.) * @title The client server is initialized to the tls1.3 version. The legacy_version in the sent serverhello message * is changed to 0x0304. The client is expected to return illegal_parameter alert. * @precon nan * @brief 4.1.3. Server Hello row23 * The client and server are initialized to the tls1.3 version, and the legacy_version in the sent serverhello * message is changed to 0x0304. The client is expected to return illegal_parameter alert. * @expect 1. The server sends an alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_LEGACY_VERSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; /* The client server is initialized to the tls1.3 version. The legacy_version in the sent serverhello message * is changed to 0x0304. */ serverMsg->version.data = 0x0304; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_LEGACY_VERSION_FUNC_TC002 * @spec legacy_version: In previous versions of TLS, this field was used for version negotiation and represented the * selected version number for the connection. In TLS 1.3, the TLS server indicates * its version using the "supported_versions" extension * (Section 4.2.1), and the legacy_version field MUST be set to * 0x0303, which is the version number for TLS 1.2. (See Appendix D * for details about backward compatibility.) * @title The client server is initialized to the tls1.3 version, and the legacy_version in the sent serverhello * message is changed to 0x0302. The client is expected to return illegal_parameter alert. * @precon nan * @brief 4.1.3. Server Hello row23 * The client and server are initialized to tls1.3 and the legacy_version in the sent serverhello message is * changed to 0x0302. The client is expected to return illegal_parameter alert. * @expect 1. The server sends an alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_LEGACY_VERSION_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; /* The client server is initialized to the tls1.3 version, and the legacy_version in the sent serverhello * message is changed to 0x0302. */ serverMsg->version.data = 0x0302; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_COMPRESSION_METHOD_FUNC_TC001 * @spec legacy_compression_method: A single byte which MUST have the * value 0. * @title Construct serverhello compression algorithm. The value is 1, indicating that the server returns * illegal_parameter alert. * @precon nan * @brief 4.1.3. Server Hello row27 * Construct the serverhello compression algorithm with a one-byte value. The server returns the * illegal_parameter alert message. * @expect 1. The server sends an alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_COMPRESSION_METHOD_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; /* Construct serverhello compression algorithm. The value is 1 */ serverMsg->compressionMethod.data = 0x01; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_PARSE_COMPRESSION_METHOD_ERR); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_EXTENSION_FUNC_TC001 * @spec extensions: A list of extensions. The ServerHello MUST only include * extensions which are required to establish the cryptographic * context and negotiate the protocol version. All TLS 1.3 * ServerHello messages MUST contain the "supported_versions" * extension. Current ServerHello messages additionally contain * either the "pre_shared_key" extension or the "key_share" * extension, or both (when using a PSK with (EC)DHE key * establishment). Other extensions (see Section 4.2) are sent * separately in the EncryptedExtensions message. * @title Initialize the client and server as tls1.3. Construct a serverhello message that carries the SNI extension. It * is expected that the connection fails to be established. * @precon nan * @brief 4.1.3. Server Hello row28 * Initialize the client server to tls1.3 and construct a serverhello message that carries the SNI extension. * The expected connection establishment fails. * @expect 1. The client sends an alert message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_EXTENSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->serverName.exState = INITIAL_FIELD; serverMsg->serverName.exType.state = INITIAL_FIELD; serverMsg->serverName.exLen.state = INITIAL_FIELD; serverMsg->serverName.exLen.data = 0x00; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNSUPPORTED_EXTENSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_EXTENSION_FUNC_TC002 * @spec extensions: A list of extensions. The ServerHello MUST only include * extensions which are required to establish the cryptographic * context and negotiate the protocol version. All TLS 1.3 * ServerHello messages MUST contain the "supported_versions" * extension. Current ServerHello messages additionally contain * either the "pre_shared_key" extension or the "key_share" * extension, or both (when using a PSK with (EC)DHE key * establishment). Other extensions (see Section 4.2) are sent * separately in the EncryptedExtensions message. * @title Initialize the client and server to tls1.3 and construct the serverhello message that does not carry the * supportedversion extension, client send illegal parameter after receive serverhello * @precon nan * @brief 4.1.3. Server Hello row28 * Initialize the client server to tls1.3 and construct the serverhello message without the supportedversion * extension, client send illegal parameter because server send a tls13 ciphersuite without supportedversion * extension * @expect 1. The client receives an alert response from the CCS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_EXTENSION_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportExtendMasterSecret = false; tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Initialize the client and server to tls1.3 and construct the serverhello message that does not carry the * supportedversion extension */ FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->supportedVersion.exState = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_RANDOM_FUNC_TC001 * @spec For reasons of backward compatibility with middleboxes (see * Appendix D.4), the HelloRetryRequest message uses the same structure * as the ServerHello, but with Random set to the special value of the * SHA-256 of "HelloRetryRequest": * * CF 21 AD 74 E5 9A 61 11 BE 1D 8C 02 1E 65 B8 91 * C2 A2 11 16 7A BB 8C 5E 07 9E 09 E2 C8 A8 33 9C * * Upon receiving a message with type server_hello, implementations MUST first examine the Random value and, * if it matches this value, process it as described in Section 4.1.4). * @title The client and server are initialized to the TLS1.3 version and construct the scenario of sending hrr * messages. After receiving hrr messages, The next packet sent by the client is expected to be a client hello * message, and the random value of the expected received hrr packet is the specified value. * @precon nan * @brief 4.1.3. Server Hello row29 * The client and server are initialized to the TLS1.3 version, construct the scenario of sending hrr messages. * After receiving hrr messages, * The next packet sent by the client is expected to be a client hello packet, and the random value of the * expected received hrr packet is the specified value. * @expect 1. Proofreading succeeded. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_RANDOM_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* The client and server are initialized to the TLS1.3 version and construct the scenario of sending hrr * messages. */ ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; const uint8_t g_hrrRandom[HS_RANDOM_SIZE] = { 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c }; ASSERT_TRUE(memcmp(serverMsg->randomValue.data, g_hrrRandom, sizeof(g_hrrRandom) / sizeof(uint8_t)) == 0); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_RANDOM_FUNC_TC002 * @spec For reasons of backward compatibility with middleboxes (see * Appendix D.4), the HelloRetryRequest message uses the same structure * as the ServerHello, but with Random set to the special value of the * SHA-256 of "HelloRetryRequest": * * CF 21 AD 74 E5 9A 61 11 BE 1D 8C 02 1E 65 B8 91 * C2 A2 11 16 7A BB 8C 5E 07 9E 09 E2 C8 A8 33 9C * * Upon receiving a message with type server_hello, implementations MUST first examine the Random value and, * if it matches this value, process it as described in Section 4.1.4). * @title The client and server are initialized to the TLS1.3 version and construct the scenario of sending hrr * messages. After receiving hrr messages, * The next packet sent by the client is expected to be client hello, and the random value of the expected * received hrr is the specified value. * @precon nan * @brief 4.1.3. Server Hello row29 * The client and server are initialized to the TLS1.3 version. The connection is established normally. The * client and server directly send the server hello packet without sending the hrr message. The random value of * the server hello packet is changed to the value specified by hrr, * The client is expected to send a client hello packet after receiving the packet. * @expect 1. It is expected that the client sends a client hello packet after receiving the packet. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_RANDOM_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; const uint8_t g_hrrRandom[HS_RANDOM_SIZE] = { 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c }; ASSERT_TRUE(memcpy_s(serverMsg->randomValue.data, sizeof(g_hrrRandom) / sizeof(uint8_t), g_hrrRandom, sizeof(g_hrrRandom) / sizeof(uint8_t)) == 0); serverMsg->keyShare.data.keyExchangeLen.state = MISSING_FIELD; serverMsg->keyShare.data.keyExchange.state = MISSING_FIELD; serverMsg->keyShare.data.group.data = HITLS_EC_GROUP_SECP521R1; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(clientTlsCtx->hsCtx->state, TRY_SEND_CLIENT_HELLO); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_DOWN_GRADE_RANDOM_FUNC_TC001 * @spec TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below * MUST check that the last 8 bytes are not equal to either of these values. * TLS 1.2 clients SHOULD also check that the last 8 bytes are not equal to the second value if the ServerHello * indicates TLS 1.1 or below. * If a match is found, the client MUST abort the handshake with an "illegal_parameter" alert. * Note: This is a change from [RFC5246], so in practice many TLS 1.2 * clients and servers will not behave as specified above. * @title The client is tls1.3, and the server is tls1.2. Construct a scenario where the last eight random bytes of * the server hello packet received by the client are equal to the specified value. The expected result is that * the connection fails to be established and the client returns the illegal_parameter alarm. * @precon nan * @brief 4.1.3. Server Hello row31 * When the client is tls1.3 and the server is tls1.2, construct the last eight random bytes of the server hello * packet received by the client equal to the specified value. In this case, the connection fails to be established * and the client returns the illegal_parameter alarm. * @expect The connection is set up normally. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_DOWN_GRADE_RANDOM_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig_c = HITLS_CFG_NewTLS13Config(); tlsConfig_c->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig_c, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetVersionSupport(tlsConfig_c, 0x00000030U); uint16_t cipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE( HITLS_CFG_SetCipherSuites(tlsConfig_c, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(tlsConfig_c != NULL); HITLS_Config *tlsConfig_s = HITLS_CFG_NewTLS12Config(); tlsConfig_s->isSupportClientVerify = true; ASSERT_TRUE(tlsConfig_s != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; /* The client is tls1.3, and the server is tls1.2. Construct a scenario where the last eight random bytes of * the server hello packet received by the client are equal to the specified value. */ const uint8_t g_tls12Downgrade[HS_DOWNGRADE_RANDOM_SIZE] = {0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01}; ASSERT_TRUE(memcpy_s(serverMsg->randomValue.data + (HS_RANDOM_SIZE - HS_DOWNGRADE_RANDOM_SIZE), sizeof(g_tls12Downgrade) / sizeof(uint8_t), g_tls12Downgrade, sizeof(g_tls12Downgrade) / sizeof(uint8_t)) == 0); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig_s); HITLS_CFG_FreeConfig(tlsConfig_c); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static void Test_ModifyServerHello(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *userData) { (void)ctx; (void)userData; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS12; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->keyShare.exState = INITIAL_FIELD; serverMsg->keyShare.exType.state = INITIAL_FIELD; serverMsg->keyShare.exLen.state = INITIAL_FIELD; serverMsg->keyShare.exLen.data = 0x00; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_RENEGOTIATION_VERSION_FUNC_TC001 * @spec A legacy TLS client performing renegotiation with TLS 1.2 or prior * and which receives a TLS 1.3 ServerHello during renegotiation MUST * abort the handshake with a "protocol_version" alert. Note that * renegotiation is not possible when TLS 1.3 has been negotiated. * @title Construct the TLS1.2 serverhello message received by the TLS1.3 serverhello message during renegotiation. * @precon nan * @brief 4.1.3. Server Hello row32 * Construct the scenario where the TLS1.2 server hello message of the TLS1.3 version is received during * renegotiation. * @expect 1. The client sends an alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SERVER_RENEGOTIATION_VERSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportRenegotiation = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); HITLS_SetClientRenegotiateSupport(server->ssl, true); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_EQ(HITLS_Renegotiate(clientTlsCtx), HITLS_SUCCESS); /* Construct the TLS1.2 serverhello message received by the TLS1.3 serverhello message during renegotiation. */ RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ModifyServerHello}; RegisterWrapper(wrapper); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_RENEGOTIATION); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNSUPPORTED_EXTENSION); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_FUNC_TC001 * @spec The server's extensions must contain "supported_versions". * Additionally, it SHOULD contain the minimal set of extensions * necessary for the client to generate a correct ClientHello pair. As * with the ServerHello, a HelloRetryRequest MUST NOT contain any * extensions that were not first offered by the client in its * ClientHello, with the exception of optionally the "cookie" (see * Section 4.2.2) extension. * @title Initialize the client and server to tls1.3. Construct the scenario where the HRR message is sent and the HRR * message does not carry the supportedversion extension, * The client is expected to perform the 1.2 handshake process and the status is TRY_RECV_CERTIFICATIONATE. * @precon nan * @brief 4.1.4. Hello Retry Request row33 * Initialize the client and server to tls1.3, construct the scenario where the HRR message is sent, and construct * the HRR message that does not carry the supportedversion extension, * The client is expected to perform the 1.2 handshake process and the status is TRY_RECV_CERTIFICATIONATE. * @expect 1. The client is in the TRY_RECV_CERTIFICATIONATE state. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportExtendMasterSecret = false; tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->supportedVersion.exState = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(clientTlsCtx->hsCtx->state, TRY_RECV_CERTIFICATE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_FUNC_TC002 * @spec The server's extensions must contain "supported_versions". * Additionally, it SHOULD contain the minimal set of extensions * necessary for the client to generate a correct ClientHello pair. As * with the ServerHello, a HelloRetryRequest MUST NOT contain any * extensions that were not first offered by the client in its * ClientHello, with the exception of optionally the "cookie" (see * Section 4.2.2) extension. * @title Initialize the client server to tls1.3, construct the scenario where the hrr message is sent, and construct the * hrr message carrying the sni extension. The client is expected to return the illegal_parameter alarm. * @precon nan * @brief 4.1.4. Hello Retry Request row33 * Initialize the client server to tls1.3, construct the scenario where the hrr message is sent, and construct the * hrr message carrying the sni extension. The client is expected to return the illegal_parameter alarm. * @expect 1. The client returns the illegal_parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->serverName.exState = INITIAL_FIELD; serverMsg->serverName.exType.state = INITIAL_FIELD; serverMsg->serverName.exLen.state = INITIAL_FIELD; serverMsg->serverName.exLen.data = 0x00; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_FUNC_TC003 * @spec The server's extensions must contain "supported_versions". * Additionally, it SHOULD contain the minimal set of extensions * necessary for the client to generate a correct ClientHello pair. As * with the ServerHello, a HelloRetryRequest MUST NOT contain any * extensions that were not first offered by the client in its * ClientHello, with the exception of optionally the "cookie" (see * Section 4.2.2) extension. * @title Initialize the client and server to tls1.3, construct the scenario where the hrr message is sent and the hrr * message does not carry the key_share extension, and the client is expected to return the illegal_parameter alarm. * @precon nan * @brief 4.1.4. Hello Retry Request row33 * Initialize the client server to tls1.3, construct the scenario where the hrr message is sent, and construct the hrr * message that does not carry the key_share extension. The client is expected to return the illegal_parameter alarm. * @expect 1. The client returns the illegal_parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); /* Initialize the client and server to tls1.3, construct the scenario where the hrr message is sent and the hrr * message does not carry the key_share extension */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->keyShare.exState = MISSING_FIELD; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_MISSING_EXTENSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC001 * @spec Upon receipt of a HelloRetryRequest, the client MUST check the * legacy_version, legacy_session_id_echo, cipher_suite, and * legacy_compression_method as specified in Section 4.1.3 and then * process the extensions, starting with determining the version using * "supported_versions". Clients MUST abort the handshake with an * "illegal_parameter" alert if the HelloRetryRequest would not result * in any change in the ClientHello. If a client receives a second * HelloRetryRequest in the same connection (i.e., where the ClientHello was itself in response to a * HelloRetryRequest), * it MUST abort the handshake with an "unexpected_message" alert. * Otherwise, the client MUST process all extensions in the HelloRetryRequest and send a second updated * ClientHello. * @title Initialize the client and server as tls1.3. Construct the scenario where two hrr messages are sent. The * client is expected to stop handshake and send unexpected_message alarms. * @precon nan * @brief 4.1.4. Hello Retry Request row34 * Initialize the client and server as tls1.3, construct the scenario where two hrr messages are sent, and the * client is expected to stop handshake and send the unexpected_message alarm. * @expect 1. The client sends the unexpected_message alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); /* Initialize the client and server as tls1.3. Construct the scenario where two hrr messages are sent. */ const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_SEND_CLIENT_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_SERVER_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_ENCRYPTED_EXTENSIONS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; const uint8_t g_hrrRandom[HS_RANDOM_SIZE] = { 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c }; ASSERT_TRUE(memcpy_s(serverMsg->randomValue.data, sizeof(g_hrrRandom) / sizeof(uint8_t), g_hrrRandom, sizeof(g_hrrRandom) / sizeof(uint8_t)) == 0); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_DUPLICATE_HELLO_RETYR_REQUEST); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC002 * @spec Upon receipt of a HelloRetryRequest, the client MUST check the * legacy_version, legacy_session_id_echo, cipher_suite, and * legacy_compression_method as specified in Section 4.1.3 and then * process the extensions, starting with determining the version using * "supported_versions". Clients MUST abort the handshake with an * "illegal_parameter" alert if the HelloRetryRequest would not result * in any change in the ClientHello. If a client receives a second * HelloRetryRequest in the same connection (i.e., where the ClientHello was itself in response to a * HelloRetryRequest), * it MUST abort the handshake with an "unexpected_message" alert. * Otherwise, the client MUST process all extensions in the HelloRetryRequest and send a second updated * ClientHello. * @title The client server is initialized to the tls1.3 version, and the legacy_version in the hrr message is changed * to 0x0304. The client is expected to return illegal_parameter alert. * @precon nan * @brief 4.1.4. Hello Retry Request row34 * The client and server are initialized to tls1.3 and the legacy_version in the hrr message is changed to * 0x0304. The client is expected to return illegal_parameter alert. * @expect 1. The client sends the unexpected_message alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->version.data = 0x0304; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC003 * @spec Upon receipt of a HelloRetryRequest, the client MUST check the * legacy_version, legacy_session_id_echo, cipher_suite, and * legacy_compression_method as specified in Section 4.1.3 and then * process the extensions, starting with determining the version using * "supported_versions". Clients MUST abort the handshake with an * "illegal_parameter" alert if the HelloRetryRequest would not result * in any change in the ClientHello. If a client receives a second * HelloRetryRequest in the same connection (i.e., where the ClientHello was itself in response to a * HelloRetryRequest), it MUST abort the handshake with an "unexpected_message" alert. * Otherwise, the client MUST process all extensions in the HelloRetryRequest and send a second updated * ClientHello. * @title The client and server are initialized to tls1.3. Change the legacy_version in the hrr message to 0x0302. The * client is expected to return illegal_parameter alert. * @precon nan * @brief 4.1.4. Hello Retry Request row34 * The client and server are initialized to tls1.3 and the legacy_version in the hrr message is changed to * 0x0302. The client is expected to return illegal_parameter alert. * @expect 1. The client sends the unexpected_message alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; /* The client and server are initialized to tls1.3. Change the legacy_version in the hrr message to 0x0302. */ serverMsg->version.data = 0x0302; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC004 * @spec Upon receipt of a HelloRetryRequest, the client MUST check the * legacy_version, legacy_session_id_echo, cipher_suite, and * legacy_compression_method as specified in Section 4.1.3 and then * process the extensions, starting with determining the version using * "supported_versions". Clients MUST abort the handshake with an * "illegal_parameter" alert if the HelloRetryRequest would not result * in any change in the ClientHello. If a client receives a second * HelloRetryRequest in the same connection (i.e., where the ClientHello was itself in response to a * HelloRetryRequest), * it MUST abort the handshake with an "unexpected_message" alert. * Otherwise, the client MUST process all extensions in the HelloRetryRequest and send a second updated * ClientHello. * @title Initialize the client and server to TLS1.3. Construct the scenario where the session_id field in the hrr is * modified. The client is expected to send an illegal parameter alarm after receiving the modification. * @precon nan * @brief 4.1.4. Hello Retry Request row34 * Initialize the client and server to TLS1.3 and construct the scenario where the hrr session_id field is * modified. The client is expected to send an illegal parameter alarm after receiving the modification. * @expect 1. The client sends an illegal parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC004() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg parsedSH = {0}; uint32_t parseLen = 0; FRAME_Type frameType = {0}; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &parsedSH, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *shMsg = &parsedSH.body.hsMsg.body.serverHello; memset_s((shMsg->sessionId.data), shMsg->sessionId.size, 1, shMsg->sessionId.size); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSH, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_ILLEGAL_SESSION_ID); EXIT: FRAME_CleanMsg(&frameType, &parsedSH); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC005 * @spec Upon receipt of a HelloRetryRequest, the client MUST check the * legacy_version, legacy_session_id_echo, cipher_suite, and * legacy_compression_method as specified in Section 4.1.3 and then * process the extensions, starting with determining the version using * "supported_versions". Clients MUST abort the handshake with an * "illegal_parameter" alert if the HelloRetryRequest would not result * in any change in the ClientHello. If a client receives a second * HelloRetryRequest in the same connection (i.e., where the ClientHello was itself in response to a * HelloRetryRequest), * it MUST abort the handshake with an "unexpected_message" alert. * Otherwise, the client MUST process all extensions in the HelloRetryRequest and send a second updated * ClientHello. * @title The client server is initialized to the TLS1.3 version, and the value of cipher_suite in the hrr message is * changed to a value other than the value provided by the client. The client is expected to return * illegal_parameter alert. * @precon nan * @brief 4.1.4. Hello Retry Request row34 * The client and server are initialized to the TLS1.3 version, and the value of cipher_suite in the hrr * message is changed to a value that is not provided by the client. The client is expected to return * illegal_parameter alert. * @expect 1. The client sends an illegal parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC005() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg parsedSH = {0}; uint32_t parseLen = 0; FRAME_Type frameType; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &parsedSH, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *shMsg = &parsedSH.body.hsMsg.body.serverHello; shMsg->cipherSuite.data = HITLS_AES_128_CCM_SHA256; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &parsedSH, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); FrameUioUserData *userData = BSL_UIO_GetUserData(client->io); uint8_t *alertBuf = userData->sndMsg.msg; uint32_t alertLen = userData->sndMsg.len; FRAME_Msg parsedAlert = {0}; uint32_t parsedAlertLen = 0; ASSERT_TRUE(FRAME_ParseTLSNonHsRecord(alertBuf, alertLen, &parsedAlert, &parsedAlertLen) == HITLS_SUCCESS); ASSERT_TRUE(parsedAlert.recType.data == REC_TYPE_ALERT); FRAME_AlertMsg *alertMsg = &parsedAlert.body.alertMsg; ASSERT_TRUE(alertMsg->alertLevel.data == ALERT_LEVEL_FATAL); ASSERT_EQ(alertMsg->alertDescription.data, ALERT_ILLEGAL_PARAMETER); EXIT: FRAME_CleanMsg(&frameType, &parsedSH); FRAME_CleanNonHsRecord(REC_TYPE_ALERT, &parsedAlert); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC006 * @spec Upon receipt of a HelloRetryRequest, the client MUST check the * legacy_version, legacy_session_id_echo, cipher_suite, and * legacy_compression_method as specified in Section 4.1.3 and then * process the extensions, starting with determining the version using * "supported_versions". Clients MUST abort the handshake with an * "illegal_parameter" alert if the HelloRetryRequest would not result * in any change in the ClientHello. If a client receives a second * HelloRetryRequest in the same connection (i.e., where the ClientHello was itself in response to a * HelloRetryRequest), * it MUST abort the handshake with an "unexpected_message" alert. * Otherwise, the client MUST process all extensions in the HelloRetryRequest and send a second updated * ClientHello. * @title Construct hrr compression algorithm. The value is 1. The server is expected to return illegal_parameter * alert. * @precon nan * @brief 4.1.4. Hello Retry Request row34 * Construct the hrr compression algorithm byte and set the value to 1. The server is expected to return * illegal_parameter alert. * @expect 1. The client sends an illegal parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_FORMAT_FUNC_TC006() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->compressionMethod.data = 0x01; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_PARSE_COMPRESSION_METHOD_ERR); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_CONTENT_FUNC_TC001 * @spec The HelloRetryRequest extensions defined in this specification are: * - supported_versions (see Section 4.2.1) * - cookie (see Section 4.2.2) * - key_share (see Section 4.2.8) * A client which receives a cipher suite that was not offered MUST * abort the handshake. Servers MUST ensure that they negotiate the * same cipher suite when receiving a conformant updated ClientHello. * Upon receiving the ServerHello, * clients MUST check that the cipher suite supplied in the ServerHello is the same as that in the * HelloRetryRequest and otherwise abort the handshake with an "illegal_parameter" alert. * @title The client and server are initialized to the TLS1.3 version. In the scenario where the hrr message is sent, * the hrr cipher suite is changed to an algorithm that is not provided by the client. The expected connection * establishment fails and the illegal_parameter alarm is returned. * @precon nan * @brief 4.1.4. Hello Retry Request row35 * The client and server are initialized to the TLS1.3 version, construct the scenario where the hrr message is * sent, and modify the hrr algorithm suite to an algorithm that is not provided by the client. In this case, * the expected connection establishment fails and the illegal_parameter alarm is returned. * @expect 1. The client returns the illegal_parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_CONTENT_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->cipherSuite.data = HITLS_RSA_WITH_AES_128_CBC_SHA; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_CONTENT_FUNC_TC002 * @spec The HelloRetryRequest extensions defined in this specification are: * - supported_versions (see Section 4.2.1) * - cookie (see Section 4.2.2) * - key_share (see Section 4.2.8) * A client which receives a cipher suite that was not offered MUST * abort the handshake. Servers MUST ensure that they negotiate the * same cipher suite when receiving a conformant updated ClientHello. * Upon receiving the ServerHello, * clients MUST check that the cipher suite supplied in the ServerHello is the same as that in the * HelloRetryRequest and otherwise abort the handshake with an "illegal_parameter" alert. * @title 2. Initialize the client and server to TLS1.3, construct the scenario where the hrr message is sent, and * change the algorithm suite for the client hello message to be sent again to the new algorithm suite. It is * expected that the connection fails to be established and the illegal_parameter alarm is returned. * @precon nan * @brief 4.1.4. Hello Retry Request row35 * 2. Initialize the client and server to TLS1.3, construct the scenario of sending hrr messages, and change * the cipher suite of the client hello message to be sent again to the new cipher suite. It is expected that * the connection fails to be established and the illegal_parameter alarm is returned. * @expect 1. The server returns the illegal_parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_CONTENT_FUNC_TC002() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_SEND_CLIENT_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, CLIENT_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); /* Initialize the client and server to TLS1.3, construct the scenario where the hrr message is sent, and * change the algorithm suite for the client hello message to be sent again to the new algorithm suite. */ FRAME_ClientHelloMsg *clientMsg = &frameMsg.body.hsMsg.body.clientHello; clientMsg->cipherSuites.data[0] = HITLS_AES_128_GCM_SHA256; clientMsg->cipherSuites.data[1] = HITLS_AES_256_GCM_SHA384; clientMsg->cipherSuites.data[2] = HITLS_CHACHA20_POLY1305_SHA256; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(server->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_CONTENT_FUNC_TC003 * @spec The HelloRetryRequest extensions defined in this specification are: * - supported_versions (see Section 4.2.1) * - cookie (see Section 4.2.2) * - key_share (see Section 4.2.8) * A client which receives a cipher suite that was not offered MUST * abort the handshake. Servers MUST ensure that they negotiate the * same cipher suite when receiving a conformant updated ClientHello. * Upon receiving the ServerHello, * clients MUST check that the cipher suite supplied in the ServerHello is the same as that in the * HelloRetryRequest and otherwise abort the handshake with an "illegal_parameter" alert. * @title 3. Initialize the client and server to TLS1.3. Construct the scenario where the HRR message is sent. Modify * the cipher suite in the serverhello message to be different from that in the HRR message. As a result, the * expected connection establishment fails and the illegal_parameter alarm is returned. * @precon nan * @brief 4.1.4. Hello Retry Request row35 * 3. The client and server are initialized to TLS1.3, construct the scenario where hrr is sent, modify the * cipher suite in serverhello and hrr to be different, and the expected connection setup fails and the * illegal_parameter alarm is returned. * @expect 1. The client returns the illegal_parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_EXTENSION_CONTENT_FUNC_TC003() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_SEND_CLIENT_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_SERVER_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_ENCRYPTED_EXTENSIONS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->cipherSuite.data = HITLS_AES_128_GCM_SHA256; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_ILLEGAL_CIPHER_SUITE); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_SUPPORT_VERSION_FUNC_TC001 * @spec The value of selected_version in the HelloRetryRequest * "supported_versions" extension MUST be retained in the ServerHello, * and a client MUST abort the handshake with an "illegal_parameter" * alert if the value changes. * @title 1. Initialize the client and server as tls1.3, construct a scenario where the supportedversion values * carried by serverhello and hrr are different, * The client is expected to return the illegal_parameter alarm. * @precon nan * @brief 4.1.4. Hello Retry Request row37 * 1. Initialize the client and server to tls1.3, construct the scenario where the supportedversion values carried * by serverhello and hrr are different, * The client is expected to return the illegal_parameter alarm. * @expect 1. The client returns the illegal_parameter alarm. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_SUPPORT_VERSION_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_CFG_SetVersionSupport(&client->ssl->config.tlsConfig, 0x00000030U); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); /* 1. Initialize the client and server to tls1.3, construct the scenario where the supportedversion values carried by serverhello and hrr are different, */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_SEND_CLIENT_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_SERVER_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_SERVER_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_ENCRYPTED_EXTENSIONS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); uint8_t *recvBuf = ioUserData->recMsg.msg; uint32_t recvLen = ioUserData->recMsg.len; ASSERT_TRUE(recvLen != 0); FRAME_Msg frameMsg = { 0 }; FRAME_Type frameType = { 0 }; uint32_t parseLen = 0; SetFrameType(&frameType, HITLS_VERSION_TLS13, REC_TYPE_HANDSHAKE, SERVER_HELLO, HITLS_KEY_EXCH_ECDHE); ASSERT_TRUE(FRAME_ParseMsg(&frameType, recvBuf, recvLen, &frameMsg, &parseLen) == HITLS_SUCCESS); FRAME_ServerHelloMsg *serverMsg = &frameMsg.body.hsMsg.body.serverHello; serverMsg->supportedVersion.data.data = 0x0303; uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_PackMsg(&frameType, &frameMsg, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ioUserData->recMsg.len = 0; ASSERT_TRUE(FRAME_TransportRecMsg(client->io, sendBuf, sendLen) == HITLS_SUCCESS); FRAME_CleanMsg(&frameType, &frameMsg); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* If the client curve is HITLS_EC_GROUP_CURVE25519 and the certificate is SECP256R1, the connection is successfully * established, indicating that the curve in tls1.3 is not associated with the certificate. */ /* BEGIN_CASE */ void SDV_TLS13_RFC8446_KeyShareGroup_TC003(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[BUF_SIZE_DTO_TEST] = {0}; uint32_t readLen; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetTls13CipherSuites(serverCtxConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_CURVE25519"); HLT_SetTls13CipherSuites(clientCtxConfig, "HITLS_AES_128_GCM_SHA256"); clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_SUCCESS); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, clientRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, BUF_SIZE_DTO_TEST, 0, BUF_SIZE_DTO_TEST) == EOK); ASSERT_TRUE(HLT_TlsRead(serverRes->ssl, readBuf, BUF_SIZE_DTO_TEST, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HRR_SUPPORT_VERSION_FUNC_TC001 * @title During the TLS1.3 HRR handshaking, application messages can not be received * @precon nan * @brief * 1. Initialize the client and server to tls1.3, construct the scenario where the supportedversion values carried * by serverhello and hrr are different, expect result 1. * 2. Send a app data message the server, expect reslut 2. * @expect 1. The client send secend client hello message. 8 2. The server send unexpected message alert. @ */ /* BEGIN_CASE */ void UT_TLS13_RFC8446_HRR_APP_RECV_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLSConfig(); tlsConfig->isSupportClientVerify = true; HITLS_CFG_SetKeyExchMode(tlsConfig, TLS13_KE_MODE_PSK_WITH_DHE); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(&(serverTlsCtx->config.tlsConfig), groups, groupsSize); /* 1. Initialize the client and server to tls1.3, construct the scenario where the supportedversion values carried by serverhello and hrr are different, */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); CONN_Deinit(serverTlsCtx); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_CHANGE_CIPHER_SPEC); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_RECV_CLIENT_HELLO); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_SEND_CLIENT_HELLO); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint32_t sendLenapp = 7; uint8_t sendBufapp[7] = {0x17, 0x03, 0x03, 0x00, 0x02, 0x05, 0x05}; uint32_t writeLen; BSL_UIO_Write(clientTlsCtx->uio, sendBufapp, sendLenapp, &writeLen); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverTlsCtx), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* IN TLS1.3, mutiple ccs can be received*/ /* BEGIN_CASE */ void UT_TLS13_RFC8446_RECV_MUTI_CCS_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_VERIFY) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); uint32_t sendLenccs = 6; uint8_t sendBufccs[6] = {0x14, 0x03, 0x03, 0x00, 0x01, 0x01}; uint32_t writeLen; for (int i = 0; i < 5; i++) { BSL_UIO_Write(serverTlsCtx->uio, sendBufccs, sendLenccs, &writeLen); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(clientTlsCtx), HITLS_REC_NORMAL_RECV_BUF_EMPTY); } ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_kex.c
C
unknown
229,523
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "rec_wrapper.h" #include "cert.h" #include "securec.h" #include "conn_init.h" #include "hitls_crypt_init.h" #include "hitls_psk.h" #include "common_func.h" #include "alert.h" #include "process.h" #include "bsl_sal.h" /* END_HEADER */ #define MAX_BUF 16384 int32_t STUB_RecConnDecrypt( TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)state; memcpy_s(data, cryptMsg->textLen, cryptMsg->text, cryptMsg->textLen); (void)data; *dataLen = cryptMsg->textLen; return HITLS_SUCCESS; } int32_t STUB_REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { (void)ctx; (void)recordType; (void)data; (void)num; return HITLS_SUCCESS; } extern int32_t __real_REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num); /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC001 * @spec - * @title The client does not support posthandshake, but receives a server certificate request * message after the connection establishment is completed. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client not to support post-handshake extension * 3. After the connection establishment is completed, the construction server sends a certificate request message to the * client * 4. Observe client behavior * @expect * 1. Initialization successful * 2. Setup successful * 3. Send successfully. * 4. The client returns alert ALERT_UNEXPECTED_MESSAGE. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC001(void) { FRAME_Init(); // Apply and initialize config HITLS_Config *c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(c_config != NULL); HITLS_Config *s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(s_config != NULL); // Set the client not to support post-handshake extension HITLS_CFG_SetPostHandshakeAuthSupport(c_config, false); HITLS_CFG_SetPostHandshakeAuthSupport(s_config, false); FRAME_LinkObj *client = FRAME_CreateLink(c_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_GetTls13DisorderHsMsg(CERTIFICATE_REQUEST, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ASSERT_EQ(REC_Write(server->ssl, REC_TYPE_HANDSHAKE, sendBuf, sendLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint8_t readbuff[READ_BUF_SIZE]; uint32_t readLen; ASSERT_TRUE(client->ssl != NULL); // The client returns alert ALERT_UNEXPECTED_MESSAGE ASSERT_EQ(HITLS_Read(client->ssl, readbuff, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC010 * @spec - * @title The server receives out-of-order messages during authentication after handshake. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client support post-handshake extension * 3. After the connection is established, the server receives the CertificateVerify message. * @expect * 1. Initialization succeeded. * 2. Set succeeded. * 3. The server sends an alert message, and the connection is interrupted. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC010(void) { FRAME_Init(); // Apply and initialize config HITLS_Config *c_config = HITLS_CFG_NewTLS13Config(); HITLS_Config *s_config = HITLS_CFG_NewTLS13Config(); // Set the client support post-handshake extension HITLS_CFG_SetPostHandshakeAuthSupport(c_config, true); HITLS_CFG_SetPostHandshakeAuthSupport(s_config, true); HITLS_CFG_SetClientVerifySupport(c_config, true); HITLS_CFG_SetClientVerifySupport(s_config, true); FRAME_LinkObj *client = FRAME_CreateLink(c_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_EQ(HITLS_VerifyClientPostHandshake(server->ssl), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); uint32_t sendLen = MAX_RECORD_LENTH; uint8_t sendBuf[MAX_RECORD_LENTH] = {0}; ASSERT_TRUE(FRAME_GetTls13DisorderHsMsg(CERTIFICATE_VERIFY, sendBuf, sendLen, &sendLen) == HITLS_SUCCESS); ASSERT_EQ(REC_Write(client->ssl, REC_TYPE_HANDSHAKE, sendBuf, sendLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC018 * @spec - * @title Invoke the HITLS_VerifyClientPostHandshake interface during connection establishment. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1 is obtained. * 2. Configure the client and server to support post-handshake extension. Expected result 3 is obtained. * 3. When a connection is established, the server is in the Try_RECV_CLIENT_HELLO state, and the * HITLS_VerifyClientPostHandshake interface is invoked. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The interface fails to be invoked. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC018(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; // Apply for and initialize the configuration file config = HITLS_CFG_NewTLS13Config(); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); // Configure the client and server to support post-handshake extension client->ssl->config.tlsConfig.isSupportPostHandshakeAuth = true; server->ssl->config.tlsConfig.isSupportPostHandshakeAuth = true; ASSERT_TRUE(client->ssl->config.tlsConfig.isSupportPostHandshakeAuth == true); ASSERT_TRUE(server->ssl->config.tlsConfig.isSupportPostHandshakeAuth == true); // he server is in the Try_RECV_CLIENT_HELLO state ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(server->ssl->hsCtx->state == TRY_RECV_CLIENT_HELLO); // the HITLS_VerifyClientPostHandshake interface is invoked ASSERT_EQ(HITLS_VerifyClientPostHandshake(client->ssl), HITLS_INVALID_INPUT); ASSERT_EQ(HITLS_VerifyClientPostHandshake(server->ssl), HITLS_MSG_HANDLE_STATE_ILLEGAL); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC019 * @spec - * @title The server does not support invoking the HITLS_VerifyClientPostHandshake interface after handshake * authentication. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1 is obtained. * 2. Configure the client to support the post-handshake extension. The server does not support the post-handshake * extension. * 3. Establish a connection. The server invokes the HITLS_VerifyClientPostHandshake interface to initiate * authentication. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The interface fails to be invoked. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC019(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; // Apply for and initialize the configuration file config = HITLS_CFG_NewTLS13Config(); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); // Configure the client to support the post-handshake extension client->ssl->config.tlsConfig.isSupportPostHandshakeAuth = true; server->ssl->config.tlsConfig.isSupportPostHandshakeAuth = false; ASSERT_TRUE(client->ssl->config.tlsConfig.isSupportPostHandshakeAuth == true); ASSERT_TRUE(server->ssl->config.tlsConfig.isSupportPostHandshakeAuth == false); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); // The server invokes the HITLS_VerifyClientPostHandshake interface to initiate authentication ASSERT_EQ(HITLS_VerifyClientPostHandshake(client->ssl), HITLS_INVALID_INPUT); ASSERT_EQ(HITLS_VerifyClientPostHandshake(server->ssl), HITLS_MSG_HANDLE_STATE_ILLEGAL); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_pha.c
C
unknown
10,630
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "securec.h" #include "conn_init.h" #include "alert.h" #include "hs_kx.h" /* END_HEADER */ #define MAX_RECORD_LENTH (20 * 1024) #define ALERT_BODY_LEN 2u const uint8_t ccsMessage[] = {0x14, 0x03, 0x03, 0x00, 0x01, 0x01}; static int32_t SendCcs(HITLS_Ctx *ctx, uint8_t *data, uint8_t len) { /** Write records. */ int32_t ret = REC_Write(ctx, REC_TYPE_CHANGE_CIPHER_SPEC, data, len); if (ret != HITLS_SUCCESS) { return ret; } /* If isFlightTransmitEnable is enabled, the stored handshake information needs to be sent. */ uint8_t isFlightTransmitEnable; (void)HITLS_GetFlightTransmitSwitch(ctx, &isFlightTransmitEnable); if (isFlightTransmitEnable == 1) { 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) { return HITLS_REC_ERR_IO_EXCEPTION; } } return HITLS_SUCCESS; } static int32_t SendAlert(HITLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { uint8_t data[ALERT_BODY_LEN]; /** Obtain the alert level. */ data[0] = level; data[1] = description; /** Write records. */ int32_t ret = REC_Write(ctx, REC_TYPE_ALERT, data, ALERT_BODY_LEN); if (ret != HITLS_SUCCESS) { return ret; } /* If isFlightTransmitEnable is enabled, the stored handshake information needs to be sent. */ uint8_t isFlightTransmitEnable; (void)HITLS_GetFlightTransmitSwitch(ctx, &isFlightTransmitEnable); if (isFlightTransmitEnable == 1) { 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) { return HITLS_REC_ERR_IO_EXCEPTION; } } return HITLS_SUCCESS; } static int32_t SendErrorAlert(HITLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { uint8_t data[2 * ALERT_BODY_LEN] = {level, description, level, description}; /** Write records. */ int32_t ret = REC_Write(ctx, REC_TYPE_ALERT, data, 2 * ALERT_BODY_LEN); if (ret != HITLS_SUCCESS) { return ret; } /* If isFlightTransmitEnable is enabled, the stored handshake information needs to be sent. */ uint8_t isFlightTransmitEnable; (void)HITLS_GetFlightTransmitSwitch(ctx, &isFlightTransmitEnable); if (isFlightTransmitEnable == 1) { 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) { return HITLS_REC_ERR_IO_EXCEPTION; } } return HITLS_SUCCESS; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC001 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 1. After the client sends a client hello message, the CCS message received by the client is not encrypted * (value: 0x01). * Discard the message and do not process the message. If the CCS message that is not encrypted is received * again (value: 0x01), the system discards the message. * 3. Before the client receives the finished message, the client receives the CCS message that is not * encrypted (value: 0x01) and discards the message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioServerData->sndMsg.msg, ioServerData->sndMsg.len) == EOK); sndMsg.len = ioServerData->sndMsg.len; ioServerData->sndMsg.len = 0; uint8_t data = 1; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 1. After the client sends a client hello message, the CCS message received by the client is not encrypted */ /* 3. Before the client receives the finished message, the client receives the CCS message that is not * encrypted */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC002 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 2. After the first connection is established, the server receives the client hello message and receives the * CCS message that is not encrypted (value: 0x01). The server discards the message and does not process * the message. * 4. If the server receives the CCS message that is not encrypted (value: 0x01) before the finished message is * received during the first connection setup, Discard the message and do not process the message. If the * CCS message that is not encrypted is received again (value: 0x01), the system sends the * unexpected_message alarm to terminate the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_CERTIFICATE) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg recMsg; ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg, ioServerData->recMsg.len) == EOK); recMsg.len = ioServerData->recMsg.len; ioServerData->recMsg.len = 0; uint8_t data = 1; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 2. After the first connection is established, the server receives the client hello message and receives the * CCS message that is not encrypted (value: 0x01). The server discards the message and does not process * the message. * 4. If the server receives the CCS message that is not encrypted (value: 0x01) before the finished message is * received during the first connection setup, Discard the message and do not process the message. If the * CCS message that is not encrypted is received again (value: 0x01) */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* The server generates the unexpected_message alarm after receiving the CCS message for the second time. */ ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC003 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 5. After the session is recovered, the clien sends the clienthello message, receives the CCS message that is * not encrypted (value: 0x01), and discards the message. * 7. The session is resumed. Before the finished message is received, the client receives a CCS message that * is not encrypted (value: 0x01). The client discards the message and does not process the message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioServerData->sndMsg.msg, ioServerData->sndMsg.len) == EOK); sndMsg.len = ioServerData->sndMsg.len; ioServerData->sndMsg.len = 0; uint8_t data = 1; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 5. After the session is recovered, the clien sends the clienthello message, receives the CCS message that is * not encrypted (value: 0x01), and discards the message. * 7. The session is resumed. Before the finished message is received, the client receives a CCS message * that is not encrypted (value: 0x01). */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC004 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 6. After the session is resumed, the server receives a CCS message that is not encrypted (value: 0x01) after * receiving the client hello message, * The message is discarded and not processed. If the CCS message is received again and the unencrypted record * (value: 0x01) is not encrypted, the alarm "unexpected_message" is sent to terminate the handshake. * 8. The session is recovered. Before the server receives the finished message, the CCS message is not * encrypted and the value is 0x01, and the message is discarded. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC004(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); ASSERT_EQ(server->ssl->hsCtx->state, TRY_RECV_FINISH); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 1); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg recMsg; ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg, ioServerData->recMsg.len) == EOK); recMsg.len = ioServerData->recMsg.len; ioServerData->recMsg.len = 0; uint8_t data = 1; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 6.After the session is resumed, the server receives a CCS message that is not encrypted (value: 0x01) after * receiving the client hello message, * 8.The session is recovered. Before the server receives the finished message, the CCS message is not * encrypted and the value is 0x01 */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* The server generates the unexpected_message alarm after receiving the CCS message for the second time. */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC005 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving unencrypted CCS messages, the system discards the messages. * @precon nan * @brief 5 Record Protocol line 181 * 9. After receiving the helloretry request, the client sends the client hello message for the second time. * The received CCS message is not encrypted (value: 0x01). * Discard the message and do not process the message. If the CCS message is received again, * discard the messages. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC005(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); /* Configure the server to support only the non-default curve. The server sends the HRR message. */ const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(tlsConfig, groups, groupsSize); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_HELLO_RETRY_REQUEST), HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioServerData->sndMsg.msg, ioServerData->sndMsg.len) == EOK); sndMsg.len = ioServerData->sndMsg.len; ioServerData->sndMsg.len = 0; uint8_t data = 1; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 9.After receiving the helloretry request, the client sends the client hello message for the second time. * The received CCS message is not encrypted (value: 0x01). * Discard the message and do not process the message. If the CCS message is received again and the * unencrypted record (value: 0x01) is received, the unexpected_message alarm is sent to terminate the handshake. */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* client will discard the ccs */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC006 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 10. After the server sends a helloretry request, the client hello message is received for the second time, * Send the unexpected_message alarm to terminate the handshake if the received CCS message is not encrypted * (value: 0x01). @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_IGNORE_CCS_FUNC_TC006(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); const uint16_t groups[] = {HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); HITLS_CFG_SetGroups(tlsConfig, groups, groupsSize); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg recMsg; ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg, ioServerData->recMsg.len) == EOK); recMsg.len = ioServerData->recMsg.len; ioServerData->recMsg.len = 0; uint8_t data = 1; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 10. After the server sends a helloretry request, the client hello message is received for the second time, * Send the unexpected_message alarm to terminate the handshake if the received CCS message is not * encrypted (value: 0x01). */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC001 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 1. After the client sends a client hello message to the client, the client sends an unexpected_message alarm * to terminate the handshake because the client receives a CCS whose value is not 0x01. * 7. Before the client receives the finised message, the client sends the unexpected_message alarm to * terminate the handshake because the client receives a CCS whose value is not 0x01. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioServerData->sndMsg.msg, ioServerData->sndMsg.len) == EOK); sndMsg.len = ioServerData->sndMsg.len; ioServerData->sndMsg.len = 0; uint8_t data = 2; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* The client receives an unencrypted CCS message (value: 0x01) and sends an unexpected_message alarm to terminate * the handshake before the client receives the finished message. */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC002 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 2. After the client sends the client hello message to the first connection setup, the client sends the * unexpected_message alarm to terminate the handshake because the encrypted CCS is received. * 9. Before the client receives the finised message, the client sends the unexpected_message alarm to * terminate the handshake because the client receives the encrypted CCS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); serverTlsCtx->recCtx->outBuf->end = 0; uint32_t hashLen = SAL_CRYPT_DigestSize(serverTlsCtx->negotiatedInfo.cipherSuiteInfo.hashAlg); ASSERT_EQ( HS_SwitchTrafficKey(serverTlsCtx, serverTlsCtx->hsCtx->serverHsTrafficSecret, hashLen, true), HITLS_SUCCESS); uint8_t data = 1; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->sndMsg.msg[0] = REC_TYPE_CHANGE_CIPHER_SPEC; FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 2. After the client sends the client hello message to the first connection setup, the client sends the * unexpected_message alarm to terminate the handshake because the encrypted CCS is received. * 9. Before the client receives the finised message, the client sends the unexpected_message alarm to * terminate the handshake because the client receives the encrypted CCS. */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC003 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 3. Before the server receives the client hello message, the server sends the unexpected_message alarm to terminate * the handshake because it receives a CCS with a value other than 0x01. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); uint8_t data = 2; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* Before the server receives the client hello message, the server sends the unexpected_message alarm to terminate * the handshake because the server receives a CCS with a value other than 0x01. */ ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC004 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 4. After the first connection is established, the server receives the client hello message and receives the * CCS whose value is not 0x01. Therefore, the server sends the unexpected_message alarm to terminate the * handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC004(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_CERTIFICATE) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg recMsg; ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg, ioServerData->recMsg.len) == EOK); recMsg.len = ioServerData->recMsg.len; ioServerData->recMsg.len = 0; uint8_t data = 2; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 4.After the first connection is established, the server receives the client hello message and receives the * CCS whose value is not 0x01. Therefore, the server sends the unexpected_message alarm to terminate the * handshake. */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC005 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 5. After the first connection is established, the server receives the client hello message and receives the * encrypted CCS. Therefore, the server sends the unexpected_message alarm to terminate the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC005(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CERTIFICATE) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg recMsg; ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg, ioServerData->recMsg.len) == EOK); recMsg.len = ioServerData->recMsg.len; ioServerData->recMsg.len = 0; clientTlsCtx->recCtx->outBuf->end = 0; uint32_t hashLen = SAL_CRYPT_DigestSize(clientTlsCtx->negotiatedInfo.cipherSuiteInfo.hashAlg); ASSERT_EQ( HS_SwitchTrafficKey(clientTlsCtx, clientTlsCtx->hsCtx->serverHsTrafficSecret, hashLen, true), HITLS_SUCCESS); /* Construct a non-0x1 CCS packet. */ uint8_t data = 1; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->sndMsg.msg[0] = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* After the first connection is established, the server receives the client hello message and receives the * encrypted CCS. Therefore, the server sends the unexpected_message alarm to terminate the handshake. */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC006 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 8. After the client receives the finised message, the client sends the unexpected_message alarm to terminate * the handshake because it receives a CCS whose value is not 0x01. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC006(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->sndMsg.len = sizeof(ccsMessage); memcpy_s(ioServerData->sndMsg.msg, ioServerData->sndMsg.len, ccsMessage, sizeof(ccsMessage)); ioServerData->sndMsg.msg[5] = 0x2; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 8. After the client receives the finised message, the client sends the unexpected_message alarm to terminate * the handshake because it receives a CCS whose value is not 0x01. */ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC007 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 9. After the client receives the finised message, the client sends the unexpected_message alarm to terminate * the handshake because the client receives the encrypted CCS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC007(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); uint8_t data = 1; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ioServerData->sndMsg.msg[0] = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 9. After the client receives the finised message, the client sends the unexpected_message alarm to terminate * the handshake because the client receives the encrypted CCS */ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC008 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 10. After the session is resumed, the client sends the unexpected_message alarm to terminate the handshake * because the client receives a CCS with a value other than 0x01. * 15. Before the session is recovered, the client receives a CCS whose value is not 0x01. Therefore, the * client sends the unexpected_message alarm to terminate the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC008(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg sndMsg; ASSERT_TRUE(memcpy_s(sndMsg.msg, MAX_RECORD_LENTH, ioServerData->sndMsg.msg, ioServerData->sndMsg.len) == EOK); sndMsg.len = ioServerData->sndMsg.len; ioServerData->sndMsg.len = 0; uint8_t data = 2; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 10. After the session is resumed, the client sends the unexpected_message alarm to terminate the handshake * because the client receives a CCS with a value other than 0x01. * 15. Before the session is recovered, the client receives a CCS whose value is not 0x01. Therefore, the * client sends the unexpected_message alarm to terminate the handshake. */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC009 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 11. After the session is recovered, the client sends the "unexpected_message" alarm to terminate the * handshake because the client receives the encrypted CCS. * 16. The session is recovered. Before the client receives the finised message, the client sends the * "unexpected_message" alarm to terminate the handshake because the client receives the encrypted CCS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC009(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); serverTlsCtx->recCtx->outBuf->end = 0; uint32_t hashLen = SAL_CRYPT_DigestSize(serverTlsCtx->negotiatedInfo.cipherSuiteInfo.hashAlg); ASSERT_EQ( HS_SwitchTrafficKey(serverTlsCtx, serverTlsCtx->hsCtx->serverHsTrafficSecret, hashLen, true), HITLS_SUCCESS); uint8_t data = 1; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->sndMsg.msg[0] = REC_TYPE_CHANGE_CIPHER_SPEC; FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 11. After the session is recovered, the client sends the "unexpected_message" alarm to terminate the * handshake because the client receives the encrypted CCS. * 16. The session is recovered. Before the client receives the finised message, the client sends the * "unexpected_message" alarm to terminate the handshake because the client receives the encrypted CCS. */ ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC010 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 12. Before the session is recovered, the server receives a CCS with a value other than 0x01 before receiving * the client hello message. Therefore, the server sends the unexpected_message alarm to terminate the * handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC010(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); uint8_t data = 2; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 12. Before the session is recovered, the server receives a CCS with a value other than 0x01 before receiving * the client hello message. Therefore, the server sends the unexpected_message alarm to terminate the * handshake. */ ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC011 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 13. After receiving the client hello message, the server sends the unexpected_message alarm to terminate the * handshake because the server receives a CCS with a value other than 0x01. * 19. Before the session is recovered, the server sends the unexpected_message alarm to terminate the * handshake because the server receives a CCS whose value is not 0x01. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC011(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg recMsg; ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg, ioServerData->recMsg.len) == EOK); recMsg.len = ioServerData->recMsg.len; ioServerData->recMsg.len = 0; clientTlsCtx->recCtx->outBuf->end = 0; uint8_t data = 2; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 13. After receiving the client hello message, the server sends the unexpected_message alarm to terminate the * handshake because the server receives a CCS with a value other than 0x01. * 19. Before the session is recovered, the server sends the unexpected_message alarm to terminate the * handshake because the server receives a CCS whose value is not 0x01. */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC012 * @spec An implementation may receive an unencrypted record of * type change_cipher_spec consisting of the single byte * value 0x01 at any time after the first ClientHello message * has been sent or received and before the peer's Finished message * has been received and MUST simply drop it without further processing. * @title When receiving an unencrypted CCS message, the system discards the message. * @precon nan * @brief 5 Record Protocol line 181 * 14. After the session is recovered, the server sends the unexpected_message alarm to terminate the handshake * because the server receives the encrypted CCS. * 20. The session is recovered. Before the server receives the finised message, it receives the encrypted CCS. * Therefore, the server sends the "unexpected_message" alarm to terminate the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC012(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FrameMsg recMsg; ASSERT_TRUE(memcpy_s(recMsg.msg, MAX_RECORD_LENTH, ioServerData->recMsg.msg, ioServerData->recMsg.len) == EOK); recMsg.len = ioServerData->recMsg.len; ioServerData->recMsg.len = 0; clientTlsCtx->recCtx->outBuf->end = 0; uint32_t hashLen = SAL_CRYPT_DigestSize(clientTlsCtx->negotiatedInfo.cipherSuiteInfo.hashAlg); ASSERT_EQ( HS_SwitchTrafficKey(clientTlsCtx, clientTlsCtx->hsCtx->serverHsTrafficSecret, hashLen, true), HITLS_SUCCESS); uint8_t data = 1; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->sndMsg.msg[0] = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 14. After the session is recovered, the server sends the unexpected_message alarm to terminate the handshake * because the server receives the encrypted CCS. * 20. The session is recovered. Before the server receives the finised message, it receives the encrypted * CCS. Therefore, the server sends the "unexpected_message" alarm to terminate the handshake. */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC013 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 17. After the session is recovered, the client receives a CCS whose value is not 0x01 and sends the * unexpected_message alarm to terminate the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC013(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->sndMsg.len = sizeof(ccsMessage); memcpy_s(ioServerData->sndMsg.msg, ioServerData->sndMsg.len, ccsMessage, sizeof(ccsMessage)); ioServerData->sndMsg.msg[5] = 0x2; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 17. After the session is recovered, the client receives a CCS whose value is not 0x01 and sends the * unexpected_message alarm to terminate the handshake. */ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC014 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 18. After the session is recovered, the client receives the finised message and receives the encrypted CCS. * Therefore, the client sends the unexpected_message alarm to terminate the handshake. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC014(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); uint8_t data = 1; ASSERT_EQ(SendCcs(server->ssl, &data, sizeof(data)), HITLS_SUCCESS); ioServerData->sndMsg.msg[0] = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); /* 18. After the session is recovered, the client receives the finised message and receives the encrypted CCS. * Therefore, the client sends the unexpected_message alarm to terminate the handshake. */ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(clientTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC015 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 21. After the session is recovered, the server sends the unexpected_message alarm to terminate the handshake * because the server receives a CCS whose value is not 0x01. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC015(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->sndMsg.len = sizeof(ccsMessage); memcpy_s(ioClientData->sndMsg.msg, ioClientData->sndMsg.len, ccsMessage, sizeof(ccsMessage)); ioClientData->sndMsg.msg[5] = 0x2; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 21. After the session is recovered, the server sends the unexpected_message alarm to terminate the handshake * because the server receives a CCS whose value is not 0x01. */ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC016 * @spec An implementation which receives any other change_cipher_spec value or * which receives a protected change_cipher_spec record MUST * abort the handshake with an "unexpected_message" alert. * @title Send the unexpected_message alarm when receiving other CCS messages. * @precon nan * @brief 5 Record Protocol line 182 * 22. After the session is recovered, the server sends the "unexpected_message" alarm to terminate the * handshake because the server receives the encrypted CCS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_RECEIVES_OTHER_CCS_FUNC_TC016(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); clientTlsCtx = FRAME_GetTlsCtx(client); serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); uint8_t data = 1; ASSERT_EQ(SendCcs(client->ssl, &data, sizeof(data)), HITLS_SUCCESS); ioClientData->sndMsg.msg[0] = REC_TYPE_CHANGE_CIPHER_SPEC; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); /* 22. After the session is recovered, the server sends the "unexpected_message" alarm to terminate the * handshake because the server receives the encrypted CCS. */ uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(serverTlsCtx, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_RECORD_TYPE_FUNC_TC001 * @spec Handshake messages MUST NOT be interleaved with other record types. * That is, if a handshake message is split over two or more records, * there MUST NOT be any other records between them. * @title Handshake messages must not be interleaved with other record types. * @precon nan * @brief 5.1. Record Layer line 186 * 1. Handshake messages are sent to multiple records. Check whether records of other types exist between * the records. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_RECORD_TYPE_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ int32_t RecParseInnerPlaintext(TLS_Ctx *ctx, uint8_t *text, uint32_t *textLen, uint8_t *recType); int32_t STUB_RecParseInnerPlaintext(TLS_Ctx *ctx, uint8_t *text, uint32_t *textLen, uint8_t *recType) { (void)ctx; (void)text; (void)textLen; *recType = (uint8_t)REC_TYPE_APP; return HITLS_SUCCESS; } /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_RECORD_TYPE_FUNC_TC002 * @spec Handshake messages MUST NOT be interleaved with other record types. * That is, if a handshake message is split over two or more records, * there MUST NOT be any other records between them. * @title Handshake messages must not be interleaved with other record types. * @precon nan * @brief 5.1. Record Layer line 186 * 2. If multiple handshake messages are interspersed with other record (app) messages, the handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_HANDSHAKE_RECORD_TYPE_FUNC_TC002(void) { FRAME_Init(); STUB_Init(); FuncStubInfo tmpRpInfo; HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_FINISH) == HITLS_SUCCESS); STUB_Replace(&tmpRpInfo, RecParseInnerPlaintext, STUB_RecParseInnerPlaintext); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: STUB_Reset(&tmpRpInfo); HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SINGLE_ALERT_FUNC_TC001 * @spec A record with an Alert type MUST contain exactly one message. * @title A record with the Alert type must contain only one message. * @precon nan * @brief 5.1. Record Layer line 186 * 1. The client sends multiple alarm messages, and the server handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SINGLE_ALERT_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_FINISH) == HITLS_SUCCESS); clientTlsCtx->recCtx->outBuf->end = 0; FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->recMsg.len = 0; ASSERT_TRUE(SendErrorAlert(client->ssl, ALERT_LEVEL_WARNING, ALERT_NO_CERTIFICATE_RESERVED) == HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SINGLE_ALERT_FUNC_TC002 * @spec A record with an Alert type MUST contain exactly one message. * @title A record with the Alert type must contain only one message. * @precon nan * @brief 5.1. Record Layer line 186 * 2. When the server sends multiple alarm messages, the client handshake fails. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SINGLE_ALERT_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); /* Stop the client receiving the TRY_RECV_SERVER_HELLO state, and the server sending the TRY_SEND_SERVER_HELLO * state. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); serverTlsCtx->recCtx->outBuf->end = 0; ASSERT_TRUE(SendErrorAlert(server->ssl, ALERT_LEVEL_WARNING, ALERT_NO_CERTIFICATE_RESERVED) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.len = 0; ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC001 * @spec legacy_record_version: MUST be set to 0x0303 * for all records generated by a TLS 1.3 implementation * other than an initial ClientHello (i.e., one not generated * after a HelloRetryRequest), where it MAY also be 0x0301 * for compatibility purposes. This field is deprecated * and MUST be ignored for all purposes. Previous versions of * TLS would use other values in this field under some circumstances. * @title For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. * @precon nan * @brief 5.1. Record Layer line 190 * 1. In TLS1.3, legacy_record_version is 0x0303 in the record message of the CCS. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); /* The client stops receiving the TRY_RECV_ENCRYPTED_EXTENSIONS. The server sends the EE message, but the EE message * is cached because the CCS message is sent first. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_ENCRYPTED_EXTENSIONS) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_ENCRYPTED_EXTENSIONS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); FRAME_Msg frameMsg = {0}; uint8_t *buffer = ioClientData->recMsg.msg; uint32_t readLen = ioClientData->recMsg.len; uint32_t parseLen = 0; ASSERT_TRUE(ParserRecordHeader(&frameMsg, buffer, readLen, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.type, REC_TYPE_CHANGE_CIPHER_SPEC); ASSERT_TRUE(frameMsg.version == HITLS_VERSION_TLS12); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC002 * @spec legacy_record_version: MUST be set to 0x0303 * for all records generated by a TLS 1.3 implementation * other than an initial ClientHello (i.e., one not generated * after a HelloRetryRequest), where it MAY also be 0x0301 * for compatibility purposes. This field is deprecated * and MUST be ignored for all purposes. Previous versions of * TLS would use other values in this field under some circumstances. * @title For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. * @precon nan * @brief 5.1. Record Layer line 190 * 2. In TLS1.3, legacy_record_version is 0x0303 in the alert record message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(SendAlert(server->ssl, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); FRAME_Msg frameMsg = {0}; uint8_t *buffer = ioClientData->recMsg.msg; uint32_t readLen = ioClientData->recMsg.len; uint32_t parseLen = 0; ASSERT_TRUE(ParserRecordHeader(&frameMsg, buffer, readLen, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.type, REC_TYPE_ALERT); ASSERT_TRUE(frameMsg.version == HITLS_VERSION_TLS12); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC003 * @spec legacy_record_version: MUST be set to 0x0303 * for all records generated by a TLS 1.3 implementation * other than an initial ClientHello (i.e., one not generated * after a HelloRetryRequest), where it MAY also be 0x0301 * for compatibility purposes. This field is deprecated * and MUST be ignored for all purposes. Previous versions of * TLS would use other values in this field under some circumstances. * @title For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. * @precon nan * @brief 5.1. Record Layer line 190 * In 5. TLS1.3, legacy_record_version is set to 0x0301 in the record message of the init clienthello. * In 3.TLS1.3, legacy_record_version is 0x0303 in the session recovery clienthello message. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); FRAME_Msg frameMsg = {0}; uint8_t *buffer = ioServerData->recMsg.msg; uint32_t readLen = ioServerData->recMsg.len; uint32_t parseLen = 0; ASSERT_TRUE(ParserRecordHeader(&frameMsg, buffer, readLen, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.type, REC_TYPE_HANDSHAKE); /* For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. */ ASSERT_TRUE(frameMsg.version == HITLS_VERSION_TLS10); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ioServerData = BSL_UIO_GetUserData(server->io); buffer = ioServerData->recMsg.msg; readLen = ioServerData->recMsg.len; parseLen = 0; ASSERT_TRUE(ParserRecordHeader(&frameMsg, buffer, readLen, &parseLen) == HITLS_SUCCESS); ASSERT_EQ(frameMsg.type, REC_TYPE_HANDSHAKE); ASSERT_TRUE(frameMsg.version == HITLS_VERSION_TLS10); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC004 * @spec legacy_record_version: MUST be set to 0x0303 * for all records generated by a TLS 1.3 implementation * other than an initial ClientHello (i.e., one not generated * after a HelloRetryRequest), where it MAY also be 0x0301 * for compatibility purposes. This field is deprecated * and MUST be ignored for all purposes. Previous versions of * TLS would use other values in this field under some circumstances. * @title For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. * @precon nan * @brief 5.1. Record Layer line 190 * In TLS1.3, the value of legacy_record_version in the serverhello message is changed to 0xffff when the * session is recovered, * After the client receives the message, the client ignores this field and the session is successfully * restored. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC004(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); uint32_t bufOffset = 1; ioClientData->recMsg.msg[bufOffset] = 0x03; bufOffset++; ioClientData->recMsg.msg[bufOffset] = 0xff; ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 1); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC005 * @spec legacy_record_version: MUST be set to 0x0303 * for all records generated by a TLS 1.3 implementation * other than an initial ClientHello (i.e., one not generated * after a HelloRetryRequest), where it MAY also be 0x0301 * for compatibility purposes. This field is deprecated * and MUST be ignored for all purposes. Previous versions of * TLS would use other values in this field under some circumstances. * @title For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. * @precon nan * @brief 5.1. Record Layer line 190 * In TLS 7.1.3, the legacy_record_version field in the record message of the client hello message is changed to * 0x0300. After the server receives the message, the server ignores the field and the handshake is still * successful. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC005(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); uint32_t bufOffset = 1; ioClientData->recMsg.msg[bufOffset] = 0x03; bufOffset++; ioClientData->recMsg.msg[bufOffset] = 0xff; ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 1); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC006 * @spec legacy_record_version: MUST be set to 0x0303 * for all records generated by a TLS 1.3 implementation * other than an initial ClientHello (i.e., one not generated * after a HelloRetryRequest), where it MAY also be 0x0301 * for compatibility purposes. This field is deprecated * and MUST be ignored for all purposes. Previous versions of * TLS would use other values in this field under some circumstances. * @title For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. * @precon nan * @brief 5.1. Record Layer line 190 * 8. The server uses TLS1.2 and the value of legacy_record_version in the record message is 0x0303, * The client uses TLS 1.3 and the value of legacy_record_version in the record message is 0x0303. The * handshake is still successful. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC006(void) { FRAME_Init(); HITLS_Config *clientConfig = HITLS_CFG_NewTLSConfig(); HITLS_Config *serverConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(serverConfig != NULL); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(clientConfig, BSL_UIO_TCP); server = FRAME_CreateLink(serverConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC007 * @spec legacy_record_version: MUST be set to 0x0303 * for all records generated by a TLS 1.3 implementation * other than an initial ClientHello (i.e., one not generated * after a HelloRetryRequest), where it MAY also be 0x0301 * for compatibility purposes. This field is deprecated * and MUST be ignored for all purposes. Previous versions of * TLS would use other values in this field under some circumstances. * @title For all records generated by the TLS 1.3 implementation, it must be set to 0x0303, * where the initial ClientHello (i.e., records not generated after HelloRetryRequest) For compatibility * purposes, it may be 0x0301. * @precon nan * @brief 5.1. Record Layer line 190 * 9. Change TLSCiphertext.legacy_record_version in the encryption record of the app to 0xffff, * After the client receives the message, the client ignores this field and the session is still successful. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_RECORD_VERSION_FUNC_TC007(void) { FRAME_Init(); HITLS_Config *clientConfig = HITLS_CFG_NewTLSConfig(); HITLS_Config *serverConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(serverConfig != NULL); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(clientConfig, BSL_UIO_TCP); server = FRAME_CreateLink(serverConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CIPHERTEXT_LENGTH_FUNC_TC001 * @spec length: The length (in bytes) of the following TLSCiphertext. * encrypted_record, which is the sum of the lengths of the content and the padding, * plus one for the inner content type, plus any expansion added by the AEAD algorithm. * The length MUST NOT exceed 2^14 + 256 bytes. An endpoint that receives a record that * exceeds this length MUST terminate the connection with a "record_overflow" alert. * @title For TLS 1.3, the length of the ciphertext cannot exceed 2 ^ 14 + 256 bytes. * @precon nan * @brief 5.2. Record Payload Protection line 194 * 1. A connection is established. During the connection establishment, the server receives a message whose * ciphertext length is 2 ^ 14 + 257. The server is expected to send a record_overflow alarm to * terminate the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CIPHERTEXT_LENGTH_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); /* The client stops receiving the TRY_RECV_ENCRYPTED_EXTENSIONS. The server sends the EE message. However, the EE * message is cached because the CCS message is sent first. */ ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CERTIFICATE) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->recMsg.msg[3] = 0x41u; ioServerData->recMsg.msg[4] = 0x01u; /* For TLS 1.3, the length of the ciphertext cannot exceed 2 ^ 14 + 256 bytes. */ ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_REC_RECORD_OVERFLOW); ALERT_Info info = {0}; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_RECORD_OVERFLOW); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_CIPHERTEXT_LENGTH_FUNC_TC002 * @spec length: The length (in bytes) of the following TLSCiphertext. * encrypted_record, which is the sum of the lengths of the content and the padding, * plus one for the inner content type, plus any expansion added by the AEAD algorithm. * The length MUST NOT exceed 2^14 + 256 bytes. An endpoint that receives a record that * exceeds this length MUST terminate the connection with a "record_overflow" alert. * @title For TLS 1.3, the length of the ciphertext cannot exceed 2 ^ 14 + 256 bytes. * @precon nan * @brief 5.2. Record Payload Protection line 194 * 2. A connection is established. During the connection establishment, the client receives a message whose ciphertext * length is 2 ^ 14 + 257. The server is expected to send a record_overflow alarm to terminate the connection. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_CIPHERTEXT_LENGTH_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_ENCRYPTED_EXTENSIONS) == HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->hsCtx->state == TRY_SEND_ENCRYPTED_EXTENSIONS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->recMsg.msg[3] = 0x41u; ioClientData->recMsg.msg[4] = 0x01u; ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_RECORD_OVERFLOW); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_RECORD_OVERFLOW); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SEQUENCE_NUMBER_FUNC_TC001 * @spec Each sequence number is set to zero at the beginning of a connection and whenever the key is changed; * the first record transmitted under a particular traffic key MUST use sequence number 0. * @title The sequence number is 0 when the connection starts or the key changes. * @precon nan * @brief 5.3. Per-Record Nonce line 197 * 1. The client sends a finish packet and an app packet. After the seq number is not 0, the key is changed * successfully and the seq number is reset to 0. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SEQUENCE_NUMBER_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint32_t writeLen; ASSERT_TRUE(HITLS_Write(client->ssl, (uint8_t *)"Hello World", sizeof("Hello World"), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); REC_Ctx *recCtx = (REC_Ctx *)client->ssl->recCtx; ASSERT_TRUE(recCtx->writeStates.currentState->seq != 0); ASSERT_TRUE(HITLS_KeyUpdate(client->ssl, HITLS_UPDATE_REQUESTED) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(recCtx->writeStates.currentState->seq == 0); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SEQUENCE_NUMBER_FUNC_TC002 * @spec Each sequence number is set to zero at the beginning of a connection and whenever the key is changed; * the first record transmitted under a particular traffic key MUST use sequence number 0. * @title The sequence number is 0 when the connection starts or the key changes. * @precon nan * @brief 5.3. Per-Record Nonce line 197 * 2. The client sends a finish packet and an app packet. After the seq number is not 0, the key fails to be * changed and the key is updated, * The seq number is not reset to 0. (It is to be confirmed whether the seq number is updated at both ends.) @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SEQUENCE_NUMBER_FUNC_TC002(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint32_t writeLen; ASSERT_TRUE(HITLS_Write(client->ssl, (uint8_t *)"Hello World", sizeof("Hello World"), &writeLen) == HITLS_SUCCESS); REC_Ctx *recCtx = (REC_Ctx *)client->ssl->recCtx; ASSERT_TRUE(recCtx->writeStates.currentState->seq != 0); FrameUioUserData *ioClientData = BSL_UIO_GetUserData(client->io); ioClientData->sndMsg.len = 1; ASSERT_TRUE(HITLS_KeyUpdate(client->ssl, HITLS_UPDATE_REQUESTED) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_TRUE(recCtx->writeStates.currentState->seq != 0); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RFC8446_CONSISTENCY_SEQUENCE_NUMBER_FUNC_TC003 * @spec Each sequence number is set to zero at the beginning of a connection and whenever the key is changed; * the first record transmitted under a particular traffic key MUST use sequence number 0. * @title The sequence number is 0 when the connection starts or the key changes. * @precon nan * @brief 5.3. Per-Record Nonce line 197 * 1. The client sends a finish packet and an app packet. After the seq number is not 0, the key is changed * successfully and the seq number is reset to 0. @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RFC8446_CONSISTENCY_SEQUENCE_NUMBER_FUNC_TC003(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportExtendMasterSecret = true; tlsConfig->isSupportClientVerify = true; tlsConfig->isSupportNoClientCert = true; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); REC_Ctx *recCtx = (REC_Ctx *)server->ssl->recCtx; ASSERT_TRUE(recCtx->writeStates.currentState->seq != 0); ASSERT_TRUE(HITLS_KeyUpdate(server->ssl, HITLS_UPDATE_REQUESTED) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(recCtx->writeStates.currentState->seq == 0); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); uint32_t writeLen; ASSERT_TRUE(HITLS_Write(server->ssl, (uint8_t *)"Hello World", sizeof("Hello World"), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(recCtx->writeStates.currentState->seq == 1); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_frame_tls13_consistency_rfc8446_record.c
C
unknown
115,909
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "bsl_sal.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "securec.h" #include "rec_wrapper.h" #include "conn_init.h" #include "rec.h" #include "parse.h" #include "hs_msg.h" #include "hs.h" #include "alert.h" #include "hitls_type.h" #include "session_type.h" #include "hitls_crypt_init.h" #include "common_func.h" #include "hlt.h" #include "process.h" #include "rec_read.h" /* END_HEADER */ #define g_uiPort 6543 // REC_Read calls TlsRecordRead calls RecParseInnerPlaintext int32_t RecParseInnerPlaintext(TLS_Ctx *ctx, const uint8_t *text, uint32_t *textLen, uint8_t *recType); int32_t STUB_RecParseInnerPlaintext(TLS_Ctx *ctx, const uint8_t *text, uint32_t *textLen, uint8_t *recType) { (void)ctx; (void)text; (void)textLen; *recType = (uint8_t)REC_TYPE_APP; return HITLS_SUCCESS; } typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; } ResumeTestInfo; static void TestFrameChangeCerts(void *msg, void *data) { (void)data; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; FRAME_CertificateMsg *certicate = &frameMsg->body.hsMsg.body.certificate; FrameCertItem *cert = certicate->certItem->next->next; // 1 ->2 ->3 ->0 cert->next = certicate->certItem->next; // 3->2 certicate->certItem->next = cert; // 1->3 cert->next->next = NULL; // 2-> 0 } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_TWO_DISOEDER_CHAIN_CERT_FUNC_TC001 * @spec - * @title The certificate chain sent by the server contains two intermediate certificates, which are out of order * (excluding the device certificate). * @precon nan * @brief The sender' s certificate MUST come in the first CertificateEntry in the list. * 1. The certificate chain sent by the server contains two intermediate certificates, and the two intermediate * certificates are out of order. Expected result 1 is displayed. * @expect 1. The connection fails to be established. The error code is ALERT_BAD_CERTIFICATIONATE. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_TWO_DISOEDER_CHAIN_CERT_FUNC_TC001(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetCertPath(serverCtxConfig, "rsa_sha512/otherRoot.der", "rsa_sha512/otherInter.der:rsa_sha512/otherInter2.der", "rsa_sha512/otherEnd.der", "rsa_sha512/otherEnd.key.der", "NULL", "NULL"); HLT_SetClientVerifySupport(serverCtxConfig, true); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCertPath(clientCtxConfig, "rsa_sha512/otherRoot.der", "rsa_sha512/otherInter.der:rsa_sha512/otherInter2.der", "rsa_sha512/otherEnd.der", "rsa_sha512/otherEnd.key.der", "NULL", "NULL"); HLT_SetClientVerifySupport(clientCtxConfig, true); HLT_SetCipherSuites(clientCtxConfig, "HITLS_RSA_WITH_AES_256_CBC_SHA"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_FrameHandle frameHandle = { .ctx = serverRes->ssl, /* 1. The certificate chain sent by the server contains two intermediate certificates, and the two intermediate * certificates are out of order. */ .frameCallBack = TestFrameChangeCerts, .userData = NULL, .expectHsType = CERTIFICATE, .expectReType = REC_TYPE_HANDSHAKE, .ioState = EXP_NONE, .pointType = POINT_SEND, }; ASSERT_TRUE(HLT_SetFrameHandle(&frameHandle) == HITLS_SUCCESS); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) != 0); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); return; } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_MIDDLE_BOX_COMPAT_FUNC_TC001 * @spec - * @title Test TLS 1.3 connection and data transfer when middlebox compatibility mode is enabled or disabled * @precon nan * @brief * 1. The server and client are configured with middlebox compatibility mode controlled by the input parameter isMiddleBoxCompat. * 2. Establish a TLS 1.3 connection between server and client. * 3. Verify bidirectional data transmission integrity. * @expect 1. The TLS 1.3 connection is successfully established. * 2. Data sent by the server is correctly received by the client (length and content match). * 3. Data sent by the client is correctly received by the server (length and content match). @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_MIDDLE_BOX_COMPAT_FUNC_TC001(int isMiddleBoxCompat) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetClientVerifySupport(serverCtxConfig, true); HLT_SetMiddleBoxCompat(serverCtxConfig, isMiddleBoxCompat); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetClientVerifySupport(clientCtxConfig, true); HLT_SetMiddleBoxCompat(clientCtxConfig, isMiddleBoxCompat); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); uint8_t writeData[REC_MAX_PLAIN_LENGTH] = {1}; uint32_t writeLen = REC_MAX_PLAIN_LENGTH; uint8_t readData[REC_MAX_PLAIN_LENGTH] = {0}; uint32_t readLen = REC_MAX_PLAIN_LENGTH; ASSERT_EQ(HLT_ProcessTlsWrite(localProcess, serverRes, writeData, writeLen), 0); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readData, readLen, &readLen), 0); ASSERT_EQ(readLen, REC_MAX_PLAIN_LENGTH); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); ASSERT_EQ(HLT_ProcessTlsWrite(remoteProcess, clientRes, writeData, writeLen), 0); ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readData, readLen, &readLen), 0); ASSERT_EQ(readLen, REC_MAX_PLAIN_LENGTH); ASSERT_EQ(memcmp(writeData, readData, readLen), 0); EXIT: HLT_FreeAllProcess(); HLT_CleanFrameHandle(); return; } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_hlt_tls13_consistency_rfc8446_1.c
C
unknown
8,318
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "bsl_sal.h" #include "tls.h" #include "hlt.h" #include "hlt_type.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "cert.h" #include "process.h" #include "securec.h" #include "session_type.h" #include "rec_wrapper.h" #include "common_func.h" #include "conn_init.h" #include "hs_extensions.h" #include "hitls_crypt_init.h" #include "crypt_util_rand.h" #include "alert.h" /* END_HEADER */ #define PORT 23456 #define READ_BUF_SIZE (18 * 1024) typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; // Set the session to the client for session recovery. HITLS_TicketKeyCb serverKeyCb; } ResumeTestInfo; typedef struct{ char *ClientCipherSuite; char *ServerCipherSuite; char *ClientGroup; char *ServerGroup; uint8_t ClientKeyExchangeMode; uint8_t ServerKeyExchangeMode; uint8_t psk[PSK_MAX_LEN]; bool SetNothing; bool SuccessOrFail; } SetInfo; void SetConfig(HLT_Ctx_Config *clientconfig, HLT_Ctx_Config *serverconfig, SetInfo setInfo) { if ( !setInfo.SetNothing ) { // Configure the server configuration. if (setInfo.ServerCipherSuite != NULL) { HLT_SetCipherSuites(serverconfig, setInfo.ServerCipherSuite); } if (setInfo.ServerGroup != NULL) { HLT_SetGroups(serverconfig, setInfo.ServerGroup); } memcpy_s(serverconfig->psk, PSK_MAX_LEN, setInfo.psk, sizeof(setInfo.psk)); if ( (setInfo.ClientKeyExchangeMode & (TLS13_KE_MODE_PSK_WITH_DHE | TLS13_KE_MODE_PSK_ONLY)) != 0) { clientconfig->keyExchMode = setInfo.ClientKeyExchangeMode; } // Configure the client configuration. if (setInfo.ClientCipherSuite != NULL) { HLT_SetCipherSuites(clientconfig, setInfo.ClientCipherSuite); } if (setInfo.ClientGroup != NULL) { HLT_SetGroups(clientconfig, setInfo.ClientGroup); } memcpy_s(clientconfig->psk, PSK_MAX_LEN, setInfo.psk, sizeof(setInfo.psk)); if ( (setInfo.ServerKeyExchangeMode & (TLS13_KE_MODE_PSK_WITH_DHE | TLS13_KE_MODE_PSK_ONLY)) != 0) { serverconfig->keyExchMode = setInfo.ServerKeyExchangeMode; } } } void ClientCreatConnectWithPara(HLT_FrameHandle *handle, SetInfo setInfo) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; // Create a process. localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // The local client and remote server listen on the TLS connection. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the config file. SetConfig(clientConfig, serverConfig, setInfo); // Listening connection. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); // Configure the interface for constructing abnormal messages. handle->ctx = clientRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Establish a connection. if ( setInfo.SuccessOrFail ) { ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) == 0); }else { ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) != 0); } EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void ServerCreatConnectWithPara(HLT_FrameHandle *handle, SetInfo setInfo) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; // Create a process. localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // The local client and remote server listen on the TLS connection. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the config file. SetConfig(clientConfig, serverConfig, setInfo); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Insert abnormal message callback. handle->ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); // Client listening connection. clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientConfig, NULL); if ( setInfo.SuccessOrFail ) { ASSERT_TRUE(clientRes != NULL); }else { ASSERT_TRUE(clientRes == NULL); } EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } void ResumeConnectWithPara(HLT_FrameHandle *handle, SetInfo setInfo) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; int32_t cnt = 1; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); // Apply for the config context. void *clientConfig = HLT_TlsNewCtx(TLS1_3); ASSERT_TRUE(clientConfig != NULL); // Configure the session restoration function. HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, TLS1_3, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, TLS1_3, false); #endif ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { if (cnt == 2) { SetConfig(clientCtxConfig, serverCtxConfig, setInfo); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); } DataChannelParam channelParam; channelParam.port = PORT; channelParam.type = TCP; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = TCP; localProcess->connType = TCP; // The server applies for the context. int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = TCP; // Set the FD. ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); // Client, applying for context void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = TCP; // Set the FD. HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { handle->ctx = clientSsl; ASSERT_TRUE(HLT_SetFrameHandle(handle) == 0); ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); if(!setInfo.SuccessOrFail){ ASSERT_TRUE(HLT_TlsConnect(clientSsl) != 0); }else { ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); } } else { // Negotiation ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); // Data read/write ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); // Disable the connection. ASSERT_TRUE(HLT_RpcTlsClose(remoteProcess, serverSslId) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_HasTicket(session) == true); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); }cnt++; } while (cnt < 3); // Perform the connection twice. EXIT: HITLS_SESS_Free(session); HLT_CleanFrameHandle(); HLT_FreeAllProcess(); return; } static void FrameCallBack_ClientHello_PskBinder_Miss(void *msg, void *userData) { // ClientHello exception: The Binder field in the ClientHello message is lost. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ClientHelloMsg *clienthello = &frameMsg->body.hsMsg.body.clientHello; clienthello->psks.binders.state = MISSING_FIELD; clienthello->psks.binderSize.state = ASSIGNED_FIELD; clienthello->psks.binderSize.data = 0; clienthello->psks.exLen.state = INITIAL_FIELD; EXIT: return; } static void FrameCallBack_ClientHello_LegacyVersion_Unsafe(void *msg, void *userData) { // ClientHello exception: The sent ClientHello message has its LegacyVersion set to SSL3.0. HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ClientHelloMsg *clienthello = &frameMsg->body.hsMsg.body.clientHello; clienthello->version.state = ASSIGNED_FIELD; clienthello->version.data = HITLS_VERSION_SSL30; EXIT: return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_PSKBINDER_FUNC_TC002 * @brief 4.2.11-Pre-Shared Key Extension-97 * @spec the server MUST validate the corresponding binder value (see Section 4.2.11.2 below). * If this value is not present or does not validate, the server MUST abort the handshake. * @title Modify the binder of client hello so that it is lost. * @precon nan * @brief * 1. The connection is established and the session is restored. * 2. Modify the binder in the psk extension of the client hello message sent by the client so that the binder is lost. * Observe the behavior of the server. * @expect * 1. The setting is successful. * 2. The server terminates the handshake. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_PSKBINDER_FUNC_TC002() { // The connection is established and the session is restored. SetInfo setInfo = {0}; setInfo.SetNothing = 1; setInfo.SuccessOrFail = 0; HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; // Modify the binder in the psk extension of the client hello message sent by the client so that the binder is lost. // Observe the behavior of the server. handle.frameCallBack = FrameCallBack_ClientHello_PskBinder_Miss; ResumeConnectWithPara(&handle, setInfo); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_VERSION_FUNC_TC001 * @brief 4.2.11-Pre-Shared Key Extension-97 * @spec Implementations MUST NOT send a ClientHello.legacy_version or ServerHello.legacy_version set to 0x0300 or less. * Any endpoint receiving a Hello message with ClientHello.legacy_version or ServerHello.legacy_version set to * 0x0300 MUST abort the handshake with a "protocol_version" alert. * @title The server receives a client hello message whose legacy_version is 0x0300. * @precon nan * @brief * 1. Change the value of legacy_version in the client Hello message to 0x0300. * 2. Observe the server behavior. * @expect * 1. The setting is successful. * 2. The server terminates the handshake. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_LEGACY_VERSION_FUNC_TC001() { // Change the value of legacy_version in the client Hello message to 0x0300. HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Observe the server behavior. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = CLIENT_HELLO; handle.frameCallBack = FrameCallBack_ClientHello_LegacyVersion_Unsafe; handle.ctx = clientRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(&handle) == 0); ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) != 0); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ static void TEST_Server13_33_Err(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)data; (void)len; (void)bufSize; uint32_t writeLen; uint32_t sendLen = 5; if (ctx->isClient==false){ uint8_t sendBuf[5] = {*(int *)user, 0x03, 0x03, 0x00, 0x00}; for (int i = 0; i < 33; i++) { ASSERT_EQ(BSL_UIO_Write(ctx->uio, sendBuf, sendLen, &writeLen),0); } return; } EXIT: return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_EMPTY_RECORDS_FUNC_TC001 * @title 0-length CCS or handshake is received during tls13 handshake proccess. * @precon nan * @brief 1. Start a handshake with tls13 config, Expected result 1 * 2. Modify the server hello message. Expected result 2 * @expect 1. Return success * 2. Handshake fails @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_EMPTY_RECORDS_FUNC_TC001(int rec_type) { CRYPT_RandRegist(TestSimpleRand); HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 8889, true); ASSERT_TRUE(remoteProcess != NULL); // Configure link information on the server. HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); serverCtxConfig->needCheckKeyUsage = true; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &rec_type, TEST_Server13_33_Err }; RegisterWrapper(wrapper); // The server listens on the TLS link. serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); // Configure link information on the client. HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsInit(remoteProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) != 0); ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, clientRes->sslId), ALERT_FLAG_SEND); ASSERT_EQ( (ALERT_Description)HLT_RpcTlsGetAlertDescription(remoteProcess, clientRes->sslId),ALERT_UNEXPECTED_MESSAGE); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_APPDATA_MAX_LENGTH * @spec - * @title In the TLS1.3 scenario, after the link is established, the app data with the maximum length is sent. It is expected that the app data can be properly processed. * @precon nan * @brief 1.Configuring TLS1.3 Link Establishment. Expected result 1 is displayed. 2.Sending large packets. Expected result 2 is obtained. * @expect 1.Return success 2.Return success * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_APPDATA_MAX_LENGTH(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 8888, false); ASSERT_TRUE(remoteProcess != NULL); serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), 0); uint8_t writeData[REC_MAX_PLAIN_LENGTH] = {1}; uint32_t writeLen = REC_MAX_PLAIN_LENGTH; uint8_t readData[REC_MAX_PLAIN_LENGTH] = {0}; uint32_t readLen = REC_MAX_PLAIN_LENGTH; ASSERT_EQ(HLT_ProcessTlsWrite(localProcess, clientRes, writeData, writeLen) , 0); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, serverRes, readData, readLen, &readLen) , 0); ASSERT_EQ(readLen , REC_MAX_PLAIN_LENGTH); ASSERT_EQ(memcmp(writeData, readData, readLen) , 0); EXIT: HLT_FreeAllProcess(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_hlt_tls13_consistency_rfc8446_2.c
C
unknown
20,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. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "rec_wrapper.h" #include "cert.h" #include "securec.h" #include "process.h" #include "conn_init.h" #include "hitls_crypt_init.h" #include "hitls_psk.h" #include "common_func.h" #include "alert.h" #include "bsl_sal.h" /* END_HEADER */ #define MAX_BUF 16384 typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; } ResumeTestInfo; static void Test_Client_Mode(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.pskModes.exData.state = ASSIGNED_FIELD; BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientHello.pskModes.exData.data); uint16_t version[] = { 0x03, }; frameMsg.body.hsMsg.body.clientHello.pskModes.exData.data = BSL_SAL_Calloc(sizeof(version) / sizeof(uint8_t), sizeof(uint8_t)); ASSERT_EQ(memcpy_s(frameMsg.body.hsMsg.body.clientHello.pskModes.exData.data, sizeof(version), version, sizeof(version)), EOK); frameMsg.body.hsMsg.body.clientHello.keyshares.exState = MISSING_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.state = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Server_Keyshare(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.keyShare.data.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data = *(uint64_t *)user; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } #define TEST_SERVERNAME_LENGTH 20 #define BUF_SIZE_DTO_TEST 18432 #define ROOT_DER "%s/ca.der:%s/inter.der" #define INTCA_DER "%s/inter.der" #define SERVER_DER "%s/server.der" #define SERVER_KEY_DER "%s/server.key.der" #define CLIENT_DER "%s/client.der" #define CLIENT_KEY_DER "%s/client.key.der" #define IP_ADDR_MAX_LEN 16 #define BYTE_SIZE 8 #define SNI_TYPE 2 #define LARGE_SIZE 1025 static int SetCertPath(HLT_Ctx_Config *ctxConfig, const char *certStr, bool isServer) { int ret; char caCertPath[50]; char chainCertPath[30]; char eeCertPath[30]; char privKeyPath[30]; ret = sprintf_s(caCertPath, sizeof(caCertPath), ROOT_DER, certStr, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(chainCertPath, sizeof(chainCertPath), INTCA_DER, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(eeCertPath, sizeof(eeCertPath), isServer ? SERVER_DER : CLIENT_DER, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(privKeyPath, sizeof(privKeyPath), isServer ? SERVER_KEY_DER : CLIENT_KEY_DER, certStr); ASSERT_TRUE(ret > 0); HLT_SetCaCertPath(ctxConfig, (char *)caCertPath); HLT_SetChainCertPath(ctxConfig, (char *)chainCertPath); HLT_SetEeCertPath(ctxConfig, (char *)eeCertPath); HLT_SetPrivKeyPath(ctxConfig, (char *)privKeyPath); return 0; EXIT: return -1; } static void Test_Server_SVersion2(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); frameMsg.body.hsMsg.body.serverHello.supportedVersion.data.data = *(uint64_t *)user; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /* BEGIN_CASE */ void HITLS_TLS1_2_Config_SDV_23_0_5_0430(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_Mode }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); serverRes = HLT_ProcessTlsAccept(remoteProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCertPath(clientCtxConfig, "ecdsa_sha256/ca.der", "NULL", "NULL", "NULL", "NULL", "NULL"); clientRes = HLT_ProcessTlsInit(localProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC001 * @spec - * @title Initialize the client server to tls1.3 and construct the selected_group carried in the key_share extension in * the sent serverhello message. It is not the group of the keyshareentry carried in the clienthello message or * the group provided in the clienthello message. As a result, the connection setup fails. * @precon nan * @brief 4.2.8. Key Share line 72 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC001(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; uint64_t groupreturn[] = {HITLS_EC_GROUP_SM2, }; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &groupreturn, Test_Server_Keyshare }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetTls13CipherSuites(serverCtxConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1:HITLS_EC_GROUP_SECP384R1"); HLT_SetTls13CipherSuites(clientCtxConfig, "HITLS_AES_128_GCM_SHA256"); clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, clientRes->sslId), ALERT_FLAG_SEND); ASSERT_EQ(HLT_RpcTlsGetAlertLevel(remoteProcess, clientRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ(HLT_RpcTlsGetAlertDescription(remoteProcess, clientRes->sslId), ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ static void Test_Server_Keyshare1(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); ASSERT_TRUE(frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data == *(uint64_t *)user); memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC002 * @spec - * @title clientHello's supported_groups is set to secp256r1. The handshake is successful. * @precon nan * @brief 9.1. Mandatory-to-Implement Cipher Suites line 230 * @expect 1. Expected connection setup success @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC002(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[BUF_SIZE_DTO_TEST] = {0}; uint32_t readLen; uint64_t groupreturn[] = {HITLS_EC_GROUP_SECP256R1, }; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &groupreturn, Test_Server_Keyshare1 }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetTls13CipherSuites(serverCtxConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1"); HLT_SetTls13CipherSuites(clientCtxConfig, "HITLS_AES_128_GCM_SHA256"); clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_SUCCESS); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, clientRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, BUF_SIZE_DTO_TEST, 0, BUF_SIZE_DTO_TEST) == EOK); ASSERT_TRUE(HLT_TlsRead(serverRes->ssl, readBuf, BUF_SIZE_DTO_TEST, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC003 * @spec - * @title clientHello's supported_groups is set to X25519. The handshake succeeds. * @precon nan * @brief 9.1. Mandatory-to-Implement Cipher Suites line 230 * @expect 1. Expected connection setup success @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_KEYSHAREGROUP_FUNC_TC003(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[BUF_SIZE_DTO_TEST] = {0}; uint32_t readLen; uint64_t groupreturn[] = {HITLS_EC_GROUP_CURVE25519, }; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &groupreturn, Test_Server_Keyshare1 }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetTls13CipherSuites(serverCtxConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_CURVE25519"); HLT_SetTls13CipherSuites(clientCtxConfig, "HITLS_AES_128_GCM_SHA256"); clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_SUCCESS); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, clientRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, BUF_SIZE_DTO_TEST, 0, BUF_SIZE_DTO_TEST) == EOK); ASSERT_TRUE(HLT_TlsRead(serverRes->ssl, readBuf, BUF_SIZE_DTO_TEST, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ #define HS_RANDOM_SIZE 32u static const uint8_t g_hrrRandom[HS_RANDOM_SIZE] = { 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c }; static void Test_Server_Keyshare2(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); if (memcmp(frameMsg.body.hsMsg.body.serverHello.randomValue.data, g_hrrRandom, HS_RANDOM_SIZE) != 0) { frameMsg.body.hsMsg.body.serverHello.keyShare.data.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.keyShare.data.group.data = *(uint64_t *)user; } memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_NAMEDGROUP_FUNC_TC001 * @spec - * @title 1. Initialize the client and server to tls1.3, construct the scenario where ecdhe is used, construct the * scenario where hrr is sent, and construct the sent serverhello. The named group of the is different from * that in the hrr. It is expected that the client terminates the handshake and sends the illegal_parameter * alarm. * @precon nan * @brief 4.2.8. Key Share line 74 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_NAMEDGROUP_FUNC_TC001(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; uint64_t groupreturn[] = {HITLS_EC_GROUP_SM2, }; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &groupreturn, Test_Server_Keyshare2 }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetGroups(serverCtxConfig, "HITLS_EC_GROUP_CURVE25519:HITLS_EC_GROUP_SECP384R1"); HLT_SetTls13CipherSuites(serverCtxConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1:HITLS_EC_GROUP_SECP384R1"); HLT_SetTls13CipherSuites(clientCtxConfig, "HITLS_AES_128_GCM_SHA256"); clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, clientRes->sslId), ALERT_FLAG_SEND); ASSERT_EQ(HLT_RpcTlsGetAlertLevel(remoteProcess, clientRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ(HLT_RpcTlsGetAlertDescription(remoteProcess, clientRes->sslId), ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ static void Test_Server_SVersion(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientHello.cipherSuites.data); uint16_t ciphers[3] = { 0xC02C, 0x1302, 0x1303}; frameMsg.body.hsMsg.body.clientHello.cipherSuites.data = BSL_SAL_Calloc(sizeof(ciphers) / sizeof(uint16_t) + 1, sizeof(uint16_t)); ASSERT_EQ(memcpy_s(frameMsg.body.hsMsg.body.clientHello.cipherSuites.data, sizeof(ciphers), ciphers, sizeof(ciphers)), EOK); frameMsg.body.hsMsg.body.clientHello.cipherSuites.state = ASSIGNED_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC001 * @spec - * @title The supported_versions in the clientHello is extended to 0x0304 (TLS 1.3). If the server supports only 1.2, the * server returns a "protocol_version" warning and the handshake fails. * @precon nan * @brief Appendix D. Backward Compatibility line 247 * @expect * 1. The setting is successful. * 2. The setting is successful. * 3. The connection is set up successfully. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC001( ) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Server_SVersion }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ALERT_Info info = { 0 }; ALERT_GetInfo(clientRes->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC002 * @spec - * @title The supported_versions field in clientHello is extended to 0x0304 (TLS 1.3). If the server supports TLS 1.3, * the server returns serverHello, If the value of upported_versions is changed to 0x0300, the client returns the * warning "ALERT_ELLEGAL_PARAMETER" and the handshake fails. * @precon nan * @brief Appendix D. Backward Compatibility line 247 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC002(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; uint64_t versions[] = {0x0300, }; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, &versions, Test_Server_SVersion2 }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath(serverCtxConfig, "ecdsa_sha256", true); HLT_SetTls13CipherSuites(serverCtxConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath(clientCtxConfig, "ecdsa_sha256", false); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP256R1:HITLS_EC_GROUP_SECP384R1"); HLT_SetTls13CipherSuites(clientCtxConfig, "HITLS_AES_128_GCM_SHA256"); clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_MSG_HANDLE_UNSUPPORT_VERSION); ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, clientRes->sslId), ALERT_FLAG_SEND); ASSERT_EQ(HLT_RpcTlsGetAlertLevel(remoteProcess, clientRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ(HLT_RpcTlsGetAlertDescription(remoteProcess, clientRes->sslId), ALERT_ILLEGAL_PARAMETER); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ static void Test_Server_SVersion3(void *msg, void *userData) { HLT_FrameHandle *handle = (HLT_FrameHandle *)userData; FRAME_Msg *frameMsg = (FRAME_Msg *)msg; ASSERT_EQ(frameMsg->body.hsMsg.type.data, handle->expectHsType); FRAME_ServerHelloMsg *serverhello = &frameMsg->body.hsMsg.body.serverHello; serverhello->supportedVersion.exState = INITIAL_FIELD; serverhello->supportedVersion.exLen.state = INITIAL_FIELD; serverhello->supportedVersion.data.state = INITIAL_FIELD; serverhello->supportedVersion.data.data = 0x0304; FRAME_ModifyMsgInteger(HS_EX_TYPE_SUPPORTED_VERSIONS, &serverhello->supportedVersion.exType); EXIT: return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC003 * @spec - * @title clientHello version is 0x0303 and the server supports 1.3 and 1.2. In this case, the server returns * serverHello and selects version 1.2, If supported_versions is set to 0x0304, the client returns a * "ALERT_UNSUPPORTED_EXTENSION" warning and the handshake fails. * @precon nan * @brief Appendix D. Backward Compatibility line 247 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC003() { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL,"SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetVersion(serverCtxConfig, HITLS_VERSION_TLS12, HITLS_VERSION_TLS13); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL,"CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_CleanFrameHandle(); HLT_FrameHandle handle = {0}; handle.pointType = POINT_SEND; handle.userData = (void *)&handle; handle.expectReType = REC_TYPE_HANDSHAKE; handle.expectHsType = SERVER_HELLO; handle.frameCallBack = Test_Server_SVersion3; handle.ctx = serverRes->ssl; ASSERT_TRUE(HLT_SetFrameHandle(&handle) == 0); clientRes = HLT_ProcessTlsInit(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_MSG_HANDLE_UNSUPPORT_EXTENSION_TYPE); ASSERT_EQ(HLT_RpcTlsGetAlertFlag(remoteProcess, clientRes->sslId), ALERT_FLAG_SEND); ASSERT_EQ(HLT_RpcTlsGetAlertLevel(remoteProcess, clientRes->sslId), ALERT_LEVEL_FATAL); ASSERT_EQ(HLT_RpcTlsGetAlertDescription(remoteProcess, clientRes->sslId), ALERT_UNSUPPORTED_EXTENSION); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ static void Test_Server_SVersion6(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.version.data = 0x0304; frameMsg.body.hsMsg.body.clientHello.supportedVersion.exState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC010 * @spec - * @title ClientHello "supported_versions" extension does not exist, and ClientHello.legacy_version is TLS 1.3, * The server supports TLS 1.3. Check that the server aborts the handshake with the "protocol_version" alert. * @precon nan * @brief Appendix D. Backward Compatibility line 248 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC010() { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Server_SVersion6 }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL,"SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL,"CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = { 0 }; ALERT_GetInfo(clientRes->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_RECV); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC012 * @spec - * @title ClientHello "supported_versions" extension does not exist, and ClientHello.legacy_version is TLS 1.2, * The server only supports TLS 1.3. Check that the server aborts the handshake with the "protocol_version" * alert. * @precon nan * @brief Appendix D. Backward Compatibility line 248 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_SVERSION_FUNC_TC012() { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL,"SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetVersion(serverCtxConfig, HITLS_VERSION_TLS13, HITLS_VERSION_TLS13); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL,"CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_TlsConnect(clientRes->ssl), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ALERT_Info info = { 0 }; ALERT_GetInfo(clientRes->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_RECV); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_PROTOCOL_VERSION); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ static void Test_Server_MasterExtKey(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS12; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS12; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); ASSERT_TRUE(frameMsg.body.hsMsg.body.serverHello.extendedMasterSecret.exState == INITIAL_FIELD); memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_MASTEREXTKEY_FUNC_TC001 * @spec - * @title tls1.2 and tls1.3 carry the extended master key (overwrite the old and new versions). The handshake is * successful. * @precon nan * @brief Appendix D. Backward Compatibility line 244 * @expect 1. Expected connection setup failure @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_MASTEREXTKEY_FUNC_TC001() { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[BUF_SIZE_DTO_TEST] = {0}; uint32_t readLen; RecWrapper wrapper = { TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Server_MasterExtKey }; RegisterWrapper(wrapper); localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL,"SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetVersion(serverCtxConfig, HITLS_VERSION_TLS12, HITLS_VERSION_TLS13); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL,"CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsInit(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_SUCCESS); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, clientRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, BUF_SIZE_DTO_TEST, 0, BUF_SIZE_DTO_TEST) == EOK); ASSERT_TRUE(HLT_TlsRead(serverRes->ssl, readBuf, BUF_SIZE_DTO_TEST, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ static void Test_Client_PskTicket(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.psks.identities.data->identity.data[0] += 0x01; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_PSKTICKET_FUNC_TC001 * @spec - * @title After the first connection is established, the ticket value is changed during session recovery. The session * recovery is expected to fail. * @precon nan * @brief 4.6.1. New Session Ticket Message line 158 * @expect 1. Failed to restore the expected session. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_PSKTICKET_FUNC_TC001(int version, int connType) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[BUF_SIZE_DTO_TEST] = {0}; uint32_t readLen; int32_t cnt = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); clientCtxConfig->isSupportRenegotiation = false; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); serverCtxConfig->isSupportRenegotiation = false; #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = g_uiPort; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); } if (cnt != 0) { RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Client_PskTicket }; RegisterWrapper(wrapper); } ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, BUF_SIZE_DTO_TEST, 0, BUF_SIZE_DTO_TEST) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, BUF_SIZE_DTO_TEST, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_RpcTlsClose(remoteProcess, serverSslId) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); if (cnt != 0) { HITLS_SESS_Free(session); session = NULL; uint8_t isReused = 0; ASSERT_TRUE(HITLS_IsSessionReused(clientSsl, &isReused) == HITLS_SUCCESS); ASSERT_TRUE(isReused == 0); } session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); cnt++; } while (cnt < 2); EXIT: ClearWrapper(); HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_hlt_tls13_consistency_rfc8446_extensions.c
C
unknown
41,497
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "rec_wrapper.h" #include "cert.h" #include "securec.h" #include "conn_init.h" #include "hitls_crypt_init.h" #include "hitls_psk.h" #include "common_func.h" #include "alert.h" #include "process.h" #include "bsl_sal.h" /* END_HEADER */ #define PORT 6666 #define MAX_BUF_SIZE 18432 void GetStrGroup(int ConnType, int group, char** strgroup) { if (ConnType == HITLS) { switch (group) { case HITLS_FF_DHE_2048: *strgroup = "HITLS_FF_DHE_2048";break; case HITLS_FF_DHE_3072: *strgroup = "HITLS_FF_DHE_3072";break; case HITLS_FF_DHE_4096: *strgroup = "HITLS_FF_DHE_4096";break; case HITLS_FF_DHE_6144: *strgroup = "HITLS_FF_DHE_6144";break; case HITLS_FF_DHE_8192: *strgroup = "HITLS_FF_DHE_8192";break; default: break; } } else { switch (group) { case HITLS_FF_DHE_2048: *strgroup = "ffdhe2048";break; case HITLS_FF_DHE_3072: *strgroup = "ffdhe3072";break; case HITLS_FF_DHE_4096: *strgroup = "ffdhe4096";break; case HITLS_FF_DHE_6144: *strgroup = "ffdhe6144";break; case HITLS_FF_DHE_8192: *strgroup = "ffdhe8192";break; default: break; } } } void HRR_ClientGroupSetInfo(int ClientType, int group, char** clientgroup) { if (ClientType == HITLS) { switch (group) { case HITLS_FF_DHE_2048: *clientgroup = "HITLS_EC_GROUP_SECP256R1:HITLS_FF_DHE_2048";break; case HITLS_FF_DHE_3072: *clientgroup = "HITLS_EC_GROUP_SECP256R1:HITLS_FF_DHE_3072";break; case HITLS_FF_DHE_4096: *clientgroup = "HITLS_EC_GROUP_SECP256R1:HITLS_FF_DHE_4096";break; case HITLS_FF_DHE_6144: *clientgroup = "HITLS_EC_GROUP_SECP256R1:HITLS_FF_DHE_6144";break; case HITLS_FF_DHE_8192: *clientgroup = "HITLS_EC_GROUP_SECP256R1:HITLS_FF_DHE_8192";break; default: break; } } else { switch (group) { case HITLS_FF_DHE_2048: *clientgroup = "P-256:ffdhe2048";break; case HITLS_FF_DHE_3072: *clientgroup = "P-256:ffdhe3072";break; case HITLS_FF_DHE_4096: *clientgroup = "P-256:ffdhe4096";break; case HITLS_FF_DHE_6144: *clientgroup = "P-256:ffdhe6144";break; case HITLS_FF_DHE_8192: *clientgroup = "P-256:ffdhe8192";break; default: break; } } } static void Test_FFDHE_Key_ERROR(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.state = ASSIGNED_FIELD; memset_s(frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.data, frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.data, 255, frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.data ); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_FFDHE_Key_Client_DecodeError(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.state = ASSIGNED_FIELD; memset_s(frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.data, frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.data, 8, 10); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_FFDHE_KeyLen_LessThenStandard(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.keyshares.exLen.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exLen.data += (120 - 256); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShareLen.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShareLen.data += (120 - 256); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.data = 120; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.state = ASSIGNED_FIELD; BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.data); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.data = BSL_SAL_Malloc(120); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.size = 120; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_FFDHE_KeyLen_MoreThenStandard(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.keyshares.exLen.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exLen.data += (1100 - 256); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShareLen.state = INITIAL_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShareLen.data += (1100 - 256); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.data = 1100; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.state = ASSIGNED_FIELD; BSL_SAL_FREE(frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.data); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.data = BSL_SAL_Malloc(1100); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchange.size = 1100; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_FFDHE_KeyLen_Error(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = { 0 }; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = { 0 }; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.clientHello.keyshares.exKeyShares.data->keyExchangeLen.data = 128; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** * @brief tls1.3 ffdhe base testcase * base test case */ /* BEGIN_CASE */ void UT_TLS13_RFC8446_FFDHE_TC001() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; HLT_SetGroups(clientCtxConfig, "HITLS_FF_DHE_4096"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->securitylevel = 0; HLT_SetGroups(serverCtxConfig, "HITLS_FF_DHE_4096"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC001 * @spec - * @title Verifying the HRR Link Setup Function When the FFDHE Group Is Used * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Configure the client and server to support ffdhe2048, and set the client to ffdhe2048 as the second supported & group. * 3. Establish a connection and read and write data. * 4. Switch the group to ffdhe3072, ffdhe4096, ffdhe6144, and ffdhe8192. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The connection is set up successfully, and data is read and written successfully. * 4. The connection is set up successfully and data is read and written successfully. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC001(int group) { FRAME_Init(); int32_t ret; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(c_config != NULL); HITLS_Config *s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(s_config != NULL); uint16_t groups = group; uint16_t clientGroups[2] = {HITLS_EC_GROUP_SECP256R1}; clientGroups[1] = group; HITLS_CFG_SetGroups(c_config, clientGroups, 2); HITLS_CFG_SetGroups(s_config, &groups, 1); client = FRAME_CreateLink(c_config, BSL_UIO_TCP); server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ret = FRAME_CreateConnection(client, server, false, HS_STATE_BUTT); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(server->ssl->state == CM_STATE_TRANSPORTING); ASSERT_EQ(client->ssl->negotiatedInfo.negotiatedGroup, group); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_TRUE(HITLS_Write(client->ssl, data, strlen("Hello World"), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t readBuf[MAX_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(server->ssl, readBuf, MAX_BUF_SIZE, &readLen) == HITLS_SUCCESS); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC002 * @spec - * @title Verifying the FFDHE Curve Function in PSK Link Establishment * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Set the PSK mode to psk_with_dhe. * 3. Configure the client and server to support FFDHE2048. * 4. Establish a connection and read and write data. * 5. Switch the group to ffdhe3072, ffdhe4096, ffdhe6144, and ffdhe8192. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The connection is set up successfully and data is read and written successfully. * 5. The connection is successfully set up, and data is successfully read and written. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC002(int group) { FRAME_Init(); int32_t ret; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(c_config != NULL); HITLS_Config *s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(s_config != NULL); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(c_config, &cipherSuite, 1); HITLS_CFG_SetCipherSuites(s_config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(c_config, TLS13_KE_MODE_PSK_WITH_DHE); HITLS_CFG_SetKeyExchMode(s_config, TLS13_KE_MODE_PSK_WITH_DHE); uint16_t groups = group; HITLS_CFG_SetGroups(c_config, &groups, 1); HITLS_CFG_SetGroups(s_config, &groups, 1); HITLS_CFG_SetPskClientCallback(c_config, ExampleClientCb); HITLS_CFG_SetPskServerCallback(s_config, ExampleServerCb); client = FRAME_CreateLink(c_config, BSL_UIO_TCP); server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ret = FRAME_CreateConnection(client, server, false, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(server->ssl->state == CM_STATE_TRANSPORTING); ASSERT_EQ(client->ssl->negotiatedInfo.negotiatedGroup, group); ASSERT_EQ(client->ssl->negotiatedInfo.tls13BasicKeyExMode , TLS13_KE_MODE_PSK_WITH_DHE); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_TRUE(HITLS_Write(client->ssl, data, strlen("Hello World"), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t readBuf[MAX_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(server->ssl, readBuf, MAX_BUF_SIZE, &readLen) == HITLS_SUCCESS); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC003 * @spec - * @title Verifying the Function of Using the FFDHE Curve for Certificate Rejection Authentication in psk_only Mode * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Set the PSK only on the client. * 3. Set the PSK mode of the client and server to psk_with_only. * 4. Set the client and server to ffdhe2048. * 5. Establish a connection and read and write data. * 6. Switch the group to ffdhe3072, ffdhe4096, ffdhe6144, and ffdhe8192. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The setting is successful. * 5. The connection is successfully set up, and data is successfully read and written. * 6. The connection is successfully set up, and data is successfully read and written. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC003(int group) { FRAME_Init(); int32_t ret; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *c_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(c_config != NULL); HITLS_Config *s_config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(s_config != NULL); uint16_t cipherSuite = HITLS_AES_128_GCM_SHA256; HITLS_CFG_SetCipherSuites(c_config, &cipherSuite, 1); HITLS_CFG_SetCipherSuites(s_config, &cipherSuite, 1); HITLS_CFG_SetKeyExchMode(c_config, TLS13_KE_MODE_PSK_ONLY); HITLS_CFG_SetKeyExchMode(s_config, TLS13_KE_MODE_PSK_ONLY); uint16_t groups = group; HITLS_CFG_SetGroups(c_config, &groups, 1); HITLS_CFG_SetGroups(s_config, &groups, 1); ExampleSetPsk("12121212121212"); HITLS_CFG_SetPskClientCallback(c_config, ExampleClientCb); client = FRAME_CreateLink(c_config, BSL_UIO_TCP); server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ret = FRAME_CreateConnection(client, server, false, HS_STATE_BUTT); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(server->ssl->state == CM_STATE_TRANSPORTING); ASSERT_EQ(client->ssl->negotiatedInfo.negotiatedGroup, group); ASSERT_EQ(client->ssl->negotiatedInfo.tls13BasicKeyExMode , TLS13_CERT_AUTH_WITH_DHE); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_TRUE(HITLS_Write(client->ssl, data, strlen("Hello World"), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t readBuf[MAX_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(server->ssl, readBuf, MAX_BUF_SIZE, &readLen) == HITLS_SUCCESS); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC004 * @spec - * @title The key length in the keyshare file is less than the length required by the RFC. * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Configure the client and server to support ffdhe2048. * 3. Change the value of Key Exchange Length in the keyshare field in the client hello packet to 120. * 4. Establish a connection and observe the server behavior. * 5. Switch the group to ffdhe3072, ffdhe4096, ffdhe6144, and ffdhe8192, and repeat the preceding operations. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The modification is successful. * 4. The server sends an alert message to disconnect the connection. * 5. The server sends an alert message to disconnect the connection. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC004(int ClientType, int ServerType, int group) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; char *servergroup; char *clientgroup; localProcess = HLT_InitLocalProcess(ClientType); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(ServerType, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // Apply for and initialize the TLS1.3 configuration file. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the client and server to support ffdhe2048. GetStrGroup(ClientType, group, &clientgroup); GetStrGroup(ServerType, group, &servergroup); HLT_SetGroups(serverConfig, servergroup); HLT_SetGroups(clientConfig, clientgroup); // Change the value of Key Exchange Length in the keyshare field in the client hello packet to 120. RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_FFDHE_KeyLen_LessThenStandard }; RegisterWrapper(wrapper); // Establish a connection and observe the server behavior. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC005 * @spec - * @title The key length in the keyshare file is greater than the length required by the RFC. * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Configure the client and server to support FFDHE2048. * 3. Change the value of Key Exchange Length in the keyshare message sent by the client to 8800. * 4. Establish a connection and observe the server behavior. * 5. Switch groups ffdhe3072, ffdhe4096, ffdhe6144, and ffdhe8192. Repeat the preceding operations. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The modification is successful. * 5. The server sends an alert message to disconnect the connection. * 6. The server sends an alert message to disconnect the connection. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC005(int ClientType, int ServerType, int group) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; char *servergroup; char *clientgroup; localProcess = HLT_InitLocalProcess(ClientType); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(ServerType, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // Apply for and initialize the TLS1.3 configuration file. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the client and server to support FFDHE2048. GetStrGroup(ClientType, group, &clientgroup); GetStrGroup(ServerType, group, &servergroup); HLT_SetGroups(serverConfig, servergroup); HLT_SetGroups(clientConfig, clientgroup); // Change the value of Key Exchange Length in the keyshare message sent by the client to 8800. RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_FFDHE_KeyLen_MoreThenStandard }; RegisterWrapper(wrapper); // Establish a connection and observe the server behavior. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC006 * @spec - * @title The server fails to parse the key in the keyshare file. * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Configure the client and server to support FFDHE2048. * 3. Change the values of all bits of the key in the keyshare of the client hello packet to 0xff. * 4. Establish a connection and observe the server behavior. * 5. Switch groups ffdhe3072, ffdhe4096, ffdhe6144, and ffdhe8192. Repeat the preceding operations. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The modification is successful. * 4. The server sends an alert message to disconnect the connection. * 5. The server sends an alert message to disconnect the connection. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC006(int ClientType, int ServerType, int group) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; char *servergroup; char *clientgroup; localProcess = HLT_InitLocalProcess(ClientType); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(ServerType, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // Apply for and initialize the TLS1.3 configuration file. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the client and server to support FFDHE2048. GetStrGroup(ClientType, group, &clientgroup); GetStrGroup(ServerType, group, &servergroup); HLT_SetGroups(serverConfig, servergroup); HLT_SetGroups(clientConfig, clientgroup); // Change the values of all bits of the key in the keyshare of the client hello packet to 0xff. RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_FFDHE_Key_ERROR }; RegisterWrapper(wrapper); // Establish a connection and observe the server behavior. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_CRYPT_ERR_CALC_SHARED_KEY); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC007 * @spec - * @title The server successfully parses the incorrect key in keyshare. * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Configure the client and server to support the elliptic curve ffdhe2048. * 3. Change the value of the first 10 bits of the key in the keyshare of the client hello packet to 8. * 4. Establish a connection and observe the client. * 5. Switch the elliptic curve and repeat the preceding operations. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The modification is successful. * 4. The client is disconnected due to decryption failure. * 5. Client decryption fails. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC007(int ClientType, int ServerType, int group) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; char *servergroup; char *clientgroup; localProcess = HLT_InitLocalProcess(ClientType); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(ServerType, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // Apply for and initialize the TLS1.3 configuration file. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the client and server to support the elliptic curve ffdhe2048. GetStrGroup(ClientType, group, &clientgroup); GetStrGroup(ServerType, group, &servergroup); HLT_SetGroups(serverConfig, servergroup); HLT_SetGroups(clientConfig, clientgroup); // Change the value of the first 10 bits of the key in the keyshare of the client hello packet to 8. RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_FFDHE_Key_Client_DecodeError }; RegisterWrapper(wrapper); // Establish a connection and observe the client. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC008 * @spec - * @title The key value in keyshare does not match the Key Exchange Length value. Parsing failed. * @precon nan * @brief * 1. Apply for and initialize the TLS1.3 configuration file. * 2. Configure the client and server to support FFDHE2048. * 3. Change the length of the key in the keyshare of the client hello packet to 1024 bits. * 4. Establish a connection and observe the server behavior. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The modification is successful. * 4. The server sends an alert message to disconnect the connection. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_DHE_GROUP_FUNC_TC008(int ClientType, int ServerType, int group) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; char *servergroup; char *clientgroup; localProcess = HLT_InitLocalProcess(ClientType); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(ServerType, TCP, PORT, false); ASSERT_TRUE(remoteProcess != NULL); // Apply for and initialize the TLS1.3 configuration file. serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the client and server to support FFDHE2048. GetStrGroup(ClientType, group, &clientgroup); GetStrGroup(ServerType, group, &servergroup); HLT_SetGroups(serverConfig, servergroup); HLT_SetGroups(clientConfig, clientgroup); // Change the length of the key in the keyshare of the client hello packet to 1024 bits. RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_FFDHE_KeyLen_Error }; RegisterWrapper(wrapper); // Establish a connection and observe the server behavior. serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_PARSE_INVALID_MSG_LEN); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_hlt_tls13_consistency_rfc8446_ffdhe.c
C
unknown
34,822
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_tls13_consistency_rfc8446 */ #include <stdio.h> #include "stub_replace.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_uio.h" #include "tls.h" #include "hs_ctx.h" #include "pack.h" #include "send_process.h" #include "frame_link.h" #include "frame_tls.h" #include "frame_io.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "rec_wrapper.h" #include "cert.h" #include "securec.h" #include "conn_init.h" #include "hitls_crypt_init.h" #include "hitls_psk.h" #include "common_func.h" #include "alert.h" #include "process.h" #include "bsl_sal.h" /* END_HEADER */ #define MAX_BUF 16384 int32_t STUB_RecConnDecrypt( TLS_Ctx *ctx, RecConnState *state, const REC_TextInput *cryptMsg, uint8_t *data, uint32_t *dataLen) { (void)ctx; (void)state; memcpy_s(data, cryptMsg->textLen, cryptMsg->text, cryptMsg->textLen); (void)data; *dataLen = cryptMsg->textLen; return HITLS_SUCCESS; } int32_t STUB_REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num) { (void)ctx; (void)recordType; (void)data; (void)num; return HITLS_SUCCESS; } extern int32_t __real_REC_Write(TLS_Ctx *ctx, REC_Type recordType, const uint8_t *data, uint32_t num); static void Test_FinishToAPP(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, FINISHED); STUB_Replace(user, __real_REC_Write, STUB_REC_Write); memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_ServerHello_Add_PhaExtensions( HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, SERVER_HELLO); uint8_t posthandshake[] = {0x00, 0x31, 0x00, 0x00}; frameMsg.body.hsMsg.length.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.length.data += sizeof(posthandshake); frameMsg.body.hsMsg.body.serverHello.extensionLen.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.serverHello.extensionLen.data = frameMsg.body.hsMsg.body.serverHello.extensionLen.data + sizeof(posthandshake); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); ASSERT_EQ(memcpy_s(&data[*len], bufSize - *len, &posthandshake, sizeof(posthandshake)), EOK); *len += sizeof(posthandshake); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_CertificateRequest_Ctx_Zero(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE_REQUEST); frameMsg.body.hsMsg.body.certificateReq.certificateReqCtx.state = MISSING_FIELD; frameMsg.body.hsMsg.body.certificateReq.certificateReqCtxSize.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificateReq.certificateReqCtxSize.data = 0; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Certificate_Ctx_Zero(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); frameMsg.body.hsMsg.body.certificate.certificateReqCtx.state = MISSING_FIELD; frameMsg.body.hsMsg.body.certificate.certificateReqCtxSize.state = ASSIGNED_FIELD; frameMsg.body.hsMsg.body.certificate.certificateReqCtxSize.data = 0; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Certificate_Ctx_NotSame(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CERTIFICATE); frameMsg.body.hsMsg.body.certificate.certificateReqCtx.state = ASSIGNED_FIELD; *(frameMsg.body.hsMsg.body.certificate.certificateReqCtx.data) += 1; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } static void Test_Finish_Error(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, FINISHED); frameMsg.body.hsMsg.body.finished.verifyData.state = ASSIGNED_FIELD; *(frameMsg.body.hsMsg.body.finished.verifyData.data) += 1; FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; } /** * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_PHA_FUNC_TC001 * @brief tls1.3 post-handshake auth * base test case */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_PHA_FUNC_TC001() { HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); bool isBlock = true; HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, isBlock); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *config_s = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(config_s != NULL); HLT_SetPostHandshakeAuth(config_s, true); HLT_SetClientVerifySupport(config_s, true); HLT_Ctx_Config *config_c = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(config_c != NULL); HLT_SetPostHandshakeAuth(config_c, true); HLT_SetClientVerifySupport(config_c, true); HLT_Tls_Res *serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, config_s, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Tls_Res *clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, config_c, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), 0); uint8_t src[] = "Hello world!"; uint32_t readbytes = 0; uint8_t dest[READ_BUF_SIZE] = {0}; ASSERT_EQ(HLT_ProcessTlsWrite(localProcess, clientRes, src, sizeof(src)), 0); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, serverRes, dest, READ_BUF_SIZE, &readbytes), 0); ASSERT_TRUE(readbytes == sizeof(src)); ASSERT_TRUE(memcmp(src, dest, readbytes) == 0); memset_s(dest, READ_BUF_SIZE, 0, READ_BUF_SIZE); EXIT: HLT_FreeAllProcess(); return; } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC002 * @spec - * @title The client does not support post-handshake authentication, but receives the server hello message that carries * the extension. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client not to support post-handshake extension * 3. Set up a connection and modify the server hello message to carry the post-handshake extension. * 4. Observe client behavior * @expect * 1. Initialization succeeded. * 2. Set succeeded. * 3. Modification succeeded. * 4. The client returns alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC002(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, false); ASSERT_TRUE(remoteProcess != NULL); // Apply and initialize config serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Set the client not to support post-handshake extension HLT_SetPostHandshakeAuth(serverConfig, true); HLT_SetClientVerifySupport(serverConfig, true); HLT_SetPostHandshakeAuth(clientConfig, false); HLT_SetClientVerifySupport(clientConfig, true); // Set up a connection and modify the server hello message to carry the post-handshake extension. RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerHello_Add_PhaExtensions}; RegisterWrapper(wrapper); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // The client returns alert clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) != 0); EXIT: HLT_FreeAllProcess(); ClearWrapper(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC003 * @spec - * @title The client supports authentication after handshake, but receives the server hello message that carries the * extension. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client support post-handshake extension * 3. Set up a connection and modify the server hello message to carry the post-handshake extension. * 4. Observe client behavior * @expect * 1. Initialization succeeded. * 2. Set succeeded. * 3. Modification succeeded. * 4. The client returns alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC003(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, false); ASSERT_TRUE(remoteProcess != NULL); // Apply and initialize config serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Set the client support post-handshake extension HLT_SetPostHandshakeAuth(serverConfig, true); HLT_SetClientVerifySupport(serverConfig, true); HLT_SetPostHandshakeAuth(clientConfig, true); HLT_SetClientVerifySupport(clientConfig, true); // Set up a connection and modify the server hello message to carry the post-handshake extension. RecWrapper wrapper = {TRY_SEND_SERVER_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_ServerHello_Add_PhaExtensions}; RegisterWrapper(wrapper); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); // The client returns alert clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) != 0); EXIT: HLT_FreeAllProcess(); ClearWrapper(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC004 * @spec - * @title When the value of certificate_request_context in the certificate request message * after handshake authentication is 0, the client reports an error. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client support post-handshake extension * 3. After the connection establishment is completed, modify the certificate_request_context of the * certificate request message sent by the server to 0. * 4. Observe client behavior * @expect * 1. Initialization succeeded. * 2. Set succeeded. * 3. Modification succeeded. * 4. The client returns alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC004(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, false); ASSERT_TRUE(remoteProcess != NULL); // Apply and initialize config serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Set the client support post-handshake extension HLT_SetPostHandshakeAuth(serverConfig, true); HLT_SetClientVerifySupport(serverConfig, true); HLT_SetPostHandshakeAuth(clientConfig, true); HLT_SetClientVerifySupport(clientConfig, true); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), 0); ASSERT_EQ(HITLS_VerifyClientPostHandshake(serverRes->ssl), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; // modify the certificate_request_context of the certificate request message sent by the server to 0. ClearWrapper(); RecWrapper wrapper = { TRY_SEND_CERTIFICATE_REQUEST, REC_TYPE_HANDSHAKE, false, NULL, Test_CertificateRequest_Ctx_Zero}; RegisterWrapper(wrapper); ASSERT_TRUE(HLT_TlsWrite(serverRes->ssl, (uint8_t *)writeBuf, strlen(writeBuf)) == HITLS_SUCCESS); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); // The client returns alert ASSERT_TRUE(HLT_RpcTlsRead(remoteProcess, clientRes->sslId, readBuf, READ_BUF_SIZE, &readLen) == HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC005 * @spec - * @title The server reports an error when the value of certificate_request_context of the * client certificate is 0 during authentication after handshake. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client support post-handshake extension * 3. After the connection is established, the server initiates a certificate request and changes the value of * certificate_request_context in the certificate request message from the client to 0 * 4. Observe the server behavior * @expect * 1. Initialization succeeded. * 2. Set succeeded. * 3. Modification succeeded. * 4. The server returns alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC005(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, false); ASSERT_TRUE(remoteProcess != NULL); // Apply and initialize config serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Set the client support post-handshake extension HLT_SetPostHandshakeAuth(serverConfig, true); HLT_SetClientVerifySupport(serverConfig, true); HLT_SetPostHandshakeAuth(clientConfig, true); HLT_SetClientVerifySupport(clientConfig, true); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), 0); ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverRes->sslId) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; // changes the value of certificate_request_context in the certificate request message from the client to 0 ClearWrapper(); RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_Certificate_Ctx_Zero}; RegisterWrapper(wrapper); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientRes->ssl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_TlsWrite(clientRes->ssl, (uint8_t *)writeBuf, strlen(writeBuf)) == HITLS_SUCCESS); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); // The server returns alert ASSERT_EQ(HLT_RpcTlsRead(remoteProcess, serverRes->sslId, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC006 * @spec - * @title During post-handshake authentication, the certificate_request_context sent by the client is inconsistent with * that sent by the server. As a result, the server reports an error. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client support post-handshake extension * 3. After the connection is established, the server initiates a certificate request and changes the value of * certificate_request_context in the certificate request message from the client * 4. Observe the server behavior * @expect * 1. Initialization succeeded. * 2. Set succeeded. * 3. Modification succeeded. 4. The server returns alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC006(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, false); ASSERT_TRUE(remoteProcess != NULL); // Apply and initialize config serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Set the client support post-handshake extension HLT_SetPostHandshakeAuth(serverConfig, true); HLT_SetClientVerifySupport(serverConfig, true); HLT_SetPostHandshakeAuth(clientConfig, true); HLT_SetClientVerifySupport(clientConfig, true); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), 0); ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverRes->sslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; // changes the value of certificate_request_context in the certificate request message from the client ClearWrapper(); RecWrapper wrapper = {TRY_SEND_CERTIFICATE, REC_TYPE_HANDSHAKE, false, NULL, Test_Certificate_Ctx_NotSame}; RegisterWrapper(wrapper); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientRes->ssl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_TlsWrite(clientRes->ssl, (uint8_t *)writeBuf, strlen(writeBuf)) == HITLS_SUCCESS); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); // The server returns alert ASSERT_EQ(HLT_RpcTlsRead(remoteProcess, serverRes->sslId, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_INVALID_CERT_REQ_CTX); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC007 * @spec - * @title After the PSK connection is established, the certificate is authenticated after handshake. The authentication is * successful. * @precon nan * @brief * 1. Apply for and initialize the configuration file * 2. Setting the PSK on the Client and Server * 3. Configure the client and server to support post-handshake extension * 4. After the connection is established, the server sends a certificate request message for backhandshake authentication. * @expect * 1. Initialization succeeded. * 2. Setting succeeded. * 3. Setting succeeded. * 4. Authentication succeeded. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC007(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, false); ASSERT_TRUE(remoteProcess != NULL); // Apply for and initialize the configuration file serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Configure the client and server to support post-handshake extension HLT_SetPostHandshakeAuth(serverConfig, true); HLT_SetClientVerifySupport(serverConfig, true); HLT_SetPostHandshakeAuth(clientConfig, true); HLT_SetClientVerifySupport(clientConfig, true); // Setting the PSK on the Client and Server memcpy_s(clientConfig->psk, PSK_MAX_LEN, "12121212121212", sizeof("12121212121212")); memcpy_s(serverConfig->psk, PSK_MAX_LEN, "12121212121212", sizeof("12121212121212")); HLT_SetCipherSuites(clientConfig, "HITLS_AES_128_GCM_SHA256"); HLT_SetCipherSuites(serverConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), 0); // the server sends a certificate request message for backhandshake authentication. ASSERT_EQ(HITLS_VerifyClientPostHandshake(serverRes->ssl), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_TlsWrite(serverRes->ssl, (uint8_t *)writeBuf, strlen(writeBuf)) == HITLS_SUCCESS); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_EQ(HLT_RpcTlsRead(remoteProcess, clientRes->sslId, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, clientRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(serverRes->ssl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC008 * @spec - * @title The server fails to verify the finish during post-authentication. * @precon nan * @brief * 1. Apply and initialize config * 2. Set the client support post-handshake extension * 3. After the connection is established, the server initiates a certificate request and Modify the finish message sent * by the client. * 4. Observe the server behavior * @expect * 1. Initialization succeeded. * 2. Set succeeded. * 3. Modification succeeded. * 4. The server returns alert @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC008(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18889, false); ASSERT_TRUE(remoteProcess != NULL); // Apply and initialize config serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverConfig != NULL); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientConfig != NULL); // Set the client support post-handshake extension HLT_SetPostHandshakeAuth(serverConfig, true); HLT_SetClientVerifySupport(serverConfig, true); HLT_SetPostHandshakeAuth(clientConfig, true); HLT_SetClientVerifySupport(clientConfig, true); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), 0); // the server initiates a certificate request ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverRes->sslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; // Modify the finish message sent by the client. ClearWrapper(); RecWrapper wrapper = {TRY_SEND_FINISH, REC_TYPE_HANDSHAKE, false, NULL, Test_Finish_Error}; RegisterWrapper(wrapper); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverRes->sslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientRes->ssl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_TlsWrite(clientRes->ssl, (uint8_t *)writeBuf, strlen(writeBuf)) == HITLS_SUCCESS); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); // The server returns alert ASSERT_EQ(HLT_RpcTlsRead(remoteProcess, serverRes->sslId, readBuf, READ_BUF_SIZE, &readLen), HITLS_MSG_HANDLE_VERIFY_FINISHED_FAIL); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC009 * @spec - * @title Two certificates request messages are sent for backhandshake authentication, and the required certificate_request_context is inconsistent. * @precon nan * @brief 1. Apply and initialize config 2. Set the client support post-handshake extension 3. After the connection is established, the server continuously sends certificate request messages for backhandshake authentication 4. Check whether the certificate_request_context sent by the server is the same. * @expect 1. Initialization succeeded. 2. Set succeeded. 3. Constructed successfully. 4. Inconsistent certificate_request_context * @prior Level 1 * @auto TRUE+ @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC009() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); // Apply and initialize config HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Set the client support post-handshake extension clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportPostHandshakeAuth = true; ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // the server continuously sends certificate request messages ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); HITLS_Ctx *ctx = clientSsl; uint8_t ReqCtx1[1 * 1024] = {0}; memcpy_s(ReqCtx1, ctx->certificateReqCtxSize, ctx->certificateReqCtx, ctx->certificateReqCtxSize); HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); // the server continuously sends certificate request messages ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); // Inconsistent certificate_request_context ASSERT_TRUE(memcmp(ReqCtx1, ctx->certificateReqCtx, ctx->certificateReqCtxSize) != 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC011 * @spec - * @title The server does not allow the client to send an empty certificate. During authentication after handshake, * the server receives an empty certificate from the client. * @precon nan * @brief * 1. Apply for and initialize the config file. Expected result 1 is obtained. * 2. Configure the server not to allow the client to send an empty certificate. Expected result 2 is obtained. * 3. Configure the client to send an empty certificate. Expected result 3 is obtained. * 4. Configure the client and server to support post-handshake extension. Expected result 4 is obtained. * 5. Perform authentication after the connection is established. Expected result 5 is obtained. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The setting is successful. * 5. The connection is set up successfully. After receiving the client certificate, the server sends an alert message. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC011() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); // Apply for and initialize the config file HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Configure the server not to allow the client to send an empty certificate // Configure the client and server to support post-handshake extension clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportNoClientCert = false; serverCtxConfig->isSupportPostHandshakeAuth = true; // Configure the client to send an empty certificate HLT_SetCertPath( clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "NULL", "NULL", "NULL", "NULL", "NULL"); HLT_SetCertPath(serverCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // Perform authentication after the connection is established ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ret = HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); // the server sends an alert message. ASSERT_EQ(ret, HITLS_MSG_HANDLE_NO_PEER_CERTIFIACATE); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC012 * @spec - * @title The server allows the client to send an empty certificate. During authentication after handshake, * the server receives an empty certificate from the client. * @precon nan * @brief * 1. Apply for and initialize the config file. Expected result 1 is obtained. * 2. Configure the server to allow the client to send an empty certificate. Expected result 2 is obtained. * 3. Configure the client to send an empty certificate. Expected result 3 is obtained. * 4. Configure the client and server to support post-handshake extension. Expected result 4 is obtained. * 5. Perform authentication after the connection is established. Expected result 5 is obtained. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The setting is successful. * 5. The connection is successfully set up, and the server initiates authentication. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC012() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); // Apply for and initialize the config file HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Configure the server to allow the client to send an empty certificate. // Configure the client and server to support post-handshake extension clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportNoClientCert = true; serverCtxConfig->isSupportPostHandshakeAuth = true; // Configure the client to send an empty certificate HLT_SetCertPath( clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "NULL", "NULL", "NULL", "NULL", "NULL"); HLT_SetCertPath(serverCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // Perform authentication after the connection is established ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; // The connection is successfully set up, and the server initiates authentication. ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC013 * @spec - * @title The server does not set the verification failure to continue the handshake. As a result, the server * verification fails during the post-handshake authentication. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1 is obtained. * 2. Configure the client and server to support post-handshake extension. Expected result 2 is obtained. * 3. Set the server certificate to the RSA certificate and the client certificate to the ECDSA certificate. Expected * result 3 is obtained. * 4. After the connection is established, authentication is performed. Expected result 4 is obtained. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The connection is successfully established, but the server fails to authenticate the certificate. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC013() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); // Apply for and initialize the configuration file HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Configure the client and server to support post-handshake extension clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; clientCtxConfig->isSupportVerifyNone = false; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportVerifyNone = false; // Set the server certificate to the RSA certificate and the client certificate to the ECDSA certificate. HLT_SetCertPath(clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", "ecdsa/end256-sha256.key.der", "NULL", "NULL"); HLT_SetCertPath(serverCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // After the connection is established, authentication is performed ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_EQ( HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen), HITLS_CERT_ERR_VERIFY_CERT_CHAIN); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC014 * @spec - * @title The server continues the handshake if the verification fails. After the handshake, * the server continues the handshake if the verification fails. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1 is obtained. * 2. Configure the server not to verify the peer certificate. Expected result 2 is obtained. * 3. Configure the client and server to support post-handshake extension. Expected result 3 is obtained. * 4. Set the client server certificate to RSA certificate, and set the client terminal certificate to ECDSA certificate. * Expected result 4 is obtained. * 5. After the connection is established, authentication is performed. Expected result 5 is obtained. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The setting is successful. * 5. The connection is successfully established and the authentication is successful. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC014() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); // Apply for and initialize the configuration file void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Configure the server not to verify the peer certificate. // Configure the client and server to support post-handshake extension clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportVerifyNone = true; // Set the client server certificate to RSA certificate, and set the client terminal certificate to ECDSA // certificate. HLT_SetCertPath(clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "ecdsa/inter-nist521.der", "ecdsa/end256-sha256.der", "ecdsa/end256-sha256.key.der", "NULL", "NULL"); HLT_SetCertPath(serverCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // authentication is performed ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_EQ(memcmp(writeBuf, readBuf, readLen), 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC015 * @spec - * @title During the authentication after the handshake on the client, the server is * disconnected because app messages are mixed in the sent messages. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1 is obtained. * 2. Configure the client and server to support post-handshake extension. Expected result 2 is obtained. * 3. Establish a connection. The server initiates a handshake for authentication. Expected result 3 is displayed. * 4. Modify the client to send messages. Enable the client to send an app message before sending the finish message. * Expected result 4 is obtained. * 5. Observe the server behavior. Expected result 5 is obtained. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The connection is successfully set up and the server initiates authentication. * 4. The client sends the message successfully. * 5. The server sends an alert message to disconnect the connection. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC015() { STUB_Init(); FuncStubInfo tmpStubInfo; int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); // Apply for and initialize the configuration file HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Configure the client and server to support post-handshake extension clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportPostHandshakeAuth = true; HLT_SetCertPath(clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); HLT_SetCertPath(serverCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // he server initiates a handshake for authentication ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; // Enable the client to send an app message before sending the finish message. RecWrapper wrapper = {TRY_SEND_FINISH, REC_TYPE_HANDSHAKE, false, &tmpStubInfo, Test_FinishToAPP}; RegisterWrapper(wrapper); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); STUB_Reset(&tmpStubInfo); HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_EQ(HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: ClearWrapper(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC016 * @spec - * @title During authentication after handshake, the server receives multiple app messages after * sending the certificate request, and the processing is normal. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1 is obtained. * 2. Configure the client and server to support post-handshake extension. Expected result 2 is obtained. * 3. Establish a connection. The server initiates a handshake for authentication. Expected result 3 is obtained. * 4. Send an app message to the server. After the server processes the message, check the server status. * Expected result 4 is obtained. * 5. Send an app message to the server. After the server processes the message, check the server status. * Expected result 5 is obtained. * 6. Continue the authentication. Expected result 6 is obtained. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The connection is set up successfully, and the server sends a certificate request message. * 4. The server is in try_recv_certifiacates state. * 5. The server is in try_recv_certifiacates state. * 6. The authentication is successful. @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC016() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); // Apply for and initialize the configuration file HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Configure the client and server to support post-handshake extension. clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportPostHandshakeAuth = true; HLT_SetCertPath(clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); HLT_SetCertPath(serverCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // The server initiates a handshake for authentication ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); // Send an app message to the server HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); // Send an app message to the server HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); // The authentication is successful. HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC017 * @spec - * @title During post-handshake authentication, the server sends the app message after sending the certificate request * message. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1 is obtained. * 2. Configure the client and server to support post-handshake extension. Expected result 2 is obtained. * 3. Establish a connection. The server initiates a handshake for authentication. Expected result 3 is displayed. * 4. The server sends an app message. Expected result 4 is obtained. * 5. Send an app message from the server. Expected result 5 is obtained. * 6. Continue the authentication. Expected result 6 is obtained. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The connection is set up successfully, and the server sends a certificate request message. * 4. The message is sent successfully. * 5. The message is sent successfully. * 6. The authentication is successful. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_TLS_TLS13_RFC8446_CONSISTENCY_POSTHANDSHAKE_FUNC_TC017() { int version = TLS1_3; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); // Apply for and initialize the configuration file HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(clientCtxConfig != NULL); ASSERT_TRUE(serverCtxConfig != NULL); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif // Configure the client and server to support post-handshake extension. clientCtxConfig->isSupportClientVerify = true; clientCtxConfig->isSupportPostHandshakeAuth = true; serverCtxConfig->isSupportClientVerify = true; serverCtxConfig->isSupportPostHandshakeAuth = true; HLT_SetCertPath(clientCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); HLT_SetCertPath(serverCtxConfig, "rsa_sha256/ca.der:rsa_sha256/inter.der", "rsa_sha256/inter.der", "rsa_sha256/server.der", "rsa_sha256/server.key.der", "NULL", "NULL"); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); // The server initiates a handshake for authentication ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverSslId) == HITLS_SUCCESS); ; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; const char *writeBuf = "Hello world"; // The server sends an app message ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); // The server sends an app message ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); // Continue the authentication. HLT_TlsWrite(clientSsl, (uint8_t *)writeBuf, strlen(writeBuf)); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, readLen) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); EXIT: HLT_FreeAllProcess(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_sdv_hlt_tls13_consistency_rfc8446_pha.c
C
unknown
75,885
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <unistd.h> #include "securec.h" #include "bsl_sal.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "tls.h" #include "hs.h" #include "hs_ctx.h" #include "hs_state_recv.h" #include "conn_init.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "recv_process.h" #include "stub_replace.h" #include "frame_tls.h" #include "frame_msg.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "frame_io.h" #include "frame_link.h" #include "cert.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "hlt.h" #include "sctp_channel.h" #include "logger.h" #include "stub_crypt.h" #define SIGNATURE_ALGORITHMS 0x04, 0x03 /* Fields added to the SERVER_HELLOW message */ #define READ_BUF_SIZE (18 * 1024) /* Maximum length of the read message buffer */ #define TEMP_DATA_LEN 2048 /* Length of a single message */ #define ALERT_BODY_LEN 2u /* Alert data length */ typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; bool isServerExtendMasterSecret; bool isSupportRenegotiation; /* Renegotiation support flag */ bool needStopBeforeRecvCCS; /* CCS test, so that the TRY_RECV_FINISH stops before the CCS message is received */ } HandshakeTestInfo; int32_t StatusPark(HandshakeTestInfo *testInfo) { /** Construct connection */ testInfo->client = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } testInfo->server = FRAME_CreateLink(testInfo->config, BSL_UIO_TCP); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } /* Perform the CCS test so that the TRY_RECV_FINISH is stopped before the CCS message is received. * The default value is False, which does not affect the original test. */ testInfo->client->needStopBeforeRecvCCS = testInfo->isClient ? testInfo->needStopBeforeRecvCCS : false; testInfo->server->needStopBeforeRecvCCS = testInfo->isClient ? false : testInfo->needStopBeforeRecvCCS; /** Establish a connection and stop in a certain state. */ if (FRAME_CreateConnection(testInfo->client, testInfo->server, testInfo->isClient, testInfo->state) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t DefaultCfgStatusPark(HandshakeTestInfo *testInfo) { FRAME_Init(); /** Construct configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; testInfo->config->isSupportRenegotiation = testInfo->isSupportRenegotiation; return StatusPark(testInfo); } int32_t DefaultCfgStatusParkWithSuite(HandshakeTestInfo *testInfo) { FRAME_Init(); /** Construct configuration. */ testInfo->config = HITLS_CFG_NewTLS12Config(); if (testInfo->config == NULL) { return HITLS_INTERNAL_EXCEPTION; } HITLS_CFG_SetCheckKeyUsage(testInfo->config, false); uint16_t cipherSuits[] = {HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(testInfo->config, cipherSuits, sizeof(cipherSuits) / sizeof(uint16_t)); testInfo->config->isSupportExtendMasterSecret = testInfo->isSupportExtendMasterSecret; testInfo->config->isSupportClientVerify = testInfo->isSupportClientVerify; testInfo->config->isSupportNoClientCert = testInfo->isSupportNoClientCert; return StatusPark(testInfo); } #define TEST_CLIENT_SEND_FAIL 1 uint32_t g_uiPort = 8889; void TestSetCertPath(HLT_Ctx_Config *ctxConfig, char *SignatureType) { if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA1", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA1")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA256")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, RSA_SHA256_PRIV_PATH3, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA384")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA384_EE_PATH, RSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA512", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA512")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA512_EE_PATH, RSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", strlen("CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA256_EE_PATH, ECDSA_SHA256_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", strlen("CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA384_EE_PATH, ECDSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", strlen("CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA512_EE_PATH, ECDSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SHA1", strlen("CERT_SIG_SCHEME_ECDSA_SHA1")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA1_CA_PATH, ECDSA_SHA1_CHAIN_PATH, ECDSA_SHA1_EE_PATH, ECDSA_SHA1_PRIV_PATH, "NULL", "NULL"); } } void SetFrameType(FRAME_Type *frametype, uint16_t versionType, REC_Type recordType, HS_MsgType handshakeType, HITLS_KeyExchAlgo keyExType) { frametype->versionType = versionType; frametype->recordType = recordType; frametype->handshakeType = handshakeType; frametype->keyExType = keyExType; frametype->transportType = BSL_UIO_TCP; } FieldState *GetDataAddress(FRAME_Msg *data, void *member) { return (FieldState *)((size_t)data + (size_t)member); } void Test_MisClientHelloExtension(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)ctx; (void)bufSize; (void)user; FRAME_Type frameType = {0}; frameType.versionType = HITLS_VERSION_TLS13; FRAME_Msg frameMsg = {0}; frameMsg.recType.data = REC_TYPE_HANDSHAKE; frameMsg.length.data = *len; frameMsg.recVersion.data = HITLS_VERSION_TLS13; uint32_t parseLen = 0; FRAME_ParseMsgBody(&frameType, data, *len, &frameMsg, &parseLen); ASSERT_EQ(parseLen, *len); ASSERT_EQ(frameMsg.body.hsMsg.type.data, CLIENT_HELLO); FieldState *extensionState = GetDataAddress(&frameMsg, user); *extensionState = MISSING_FIELD; memset_s(data, bufSize, 0, bufSize); FRAME_PackRecordBody(&frameType, &frameMsg, data, bufSize, len); ASSERT_NE(parseLen, *len); EXIT: FRAME_CleanMsg(&frameType, &frameMsg); return; }
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/consistency/tls13/test_suite_tls13_consistency_rfc8446.base.c
C
unknown
9,390
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <errno.h> #include "securec.h" #include "bsl_sal.h" #include "frame_tls.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "frame_io.h" #include "uio_abstraction.h" #include "tls.h" #include "tls_config.h" #include "hitls_type.h" #include "hitls_func.h" #include "hitls.h" #include "pack.h" #include "bsl_err.h" #include "bsl_bytes.h" #include "custom_extensions.h" #include "frame_tls.h" #include "alert.h" #include "frame_link.h" #define CUSTOM_EXTENTIONS_TYPE_1 0x00001 #define CUSTOM_EXTENTIONS_TYPE_2 0x00002 // Simple add_cb function, allocates buffer with 1 byte length and 1 byte data int SimpleAddCb(const struct TlsCtx *ctx, uint16_t extType, uint32_t context, uint8_t **out, uint32_t *outLen, HITLS_CERT_X509 *cert, uint32_t certId, uint32_t *alert, void *addArg) { (void)ctx; (void)extType; (void)context; (void)cert; (void)certId; (void)alert; (void)addArg; *out = malloc(sizeof(uint16_t)); if (*out == NULL) { return -1; } uint32_t bufOffset = 0; (*out)[bufOffset] = 0xAA; bufOffset++; *outLen = bufOffset; return HITLS_ADD_CUSTOM_EXTENSION_RET_PACK; } // Simple free_cb function, frees the allocated data void SimpleFreeCb(const struct TlsCtx *ctx, uint16_t extType, uint32_t context, uint8_t *out, void *addArg) { (void)ctx; (void)extType; (void)context; (void)addArg; BSL_SAL_Free(out); } // Simple parse_cb function, reads the length and data, checks the data int SimpleParseCb(const struct TlsCtx *ctx, uint16_t extType, uint32_t context, const uint8_t **in, uint32_t *inLen, HITLS_CERT_X509 *cert, uint32_t certId, uint32_t *alert, void *parseArg) { (void)ctx; (void)extType; (void)context; (void)cert; (void)certId; (void)alert; (void)parseArg; if (*inLen <= 0) { return 0; } // Pass the data pointer to BSL_SAL_Dump uint8_t *dumpedData = BSL_SAL_Dump(*in, *inLen); if (dumpedData == NULL) { return 1; // Processing failed } // Check the first byte of the returned data if (dumpedData[0] != 0xAA) { BSL_SAL_Free(dumpedData); // Free memory return 1; } BSL_SAL_Free(dumpedData); // Free memory return 0; } /* END_HEADER */ /** @ * @test SDV_TLS_PACK_CUSTOM_EXTENSIONS_API_TC001 * @title Test the single extension packing function of the PackCustomExtensions interface * @precon None * @brief * 1. Initialize the TLS context and configure a single custom extension (no callback). Expected result 1. * 2. Call the PackCustomExtensions interface and verify the packing result. Expected result 2. * @expect * 1. Initialization successful. * 2. Returns HITLS_SUCCESS, packing length is 0 (no data without callback). @ */ /* BEGIN_CASE */ void SDV_TLS_PACK_CUSTOM_EXTENSIONS_API_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_NE(tlsConfig, NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_NE(ctx, NULL); uint8_t buf[1024] = {0}; uint32_t bufLen = sizeof(buf); uint32_t len = 0; uint16_t extType = CUSTOM_EXTENTIONS_TYPE_1; uint32_t context = 1; // Configure a single custom extension CustomExtMethods exts = {0}; CustomExtMethod meth = {0}; meth.extType = extType; meth.context = context; meth.addCb = NULL; // No callback meth.freeCb = NULL; // No callback exts.meths = &meth; exts.methsCount = 1; ctx->config.tlsConfig.customExts = &exts; uint32_t bufOffset = 0; uint8_t *buffAddr = &buf[0]; PackPacket pkt = {.buf = &buffAddr, .bufLen = &bufLen, .bufOffset = &bufOffset}; // Call the interface under test // Verify the return value is success ASSERT_EQ(PackCustomExtensions(ctx, &pkt, context, NULL, 0), HITLS_SUCCESS); ctx->config.tlsConfig.customExts = NULL; ASSERT_EQ(len, 0); // No data packed without add_cb EXIT: HITLS_Free(ctx); HITLS_CFG_FreeConfig(tlsConfig); return; } /* END_CASE */ /** @ * @test SDV_TLS_PARSE_CUSTOM_EXTENSIONS_API_TC001 * @title Test the single extension parsing function of the ParseCustomExtensions interface * @precon None * @brief * 1. Initialize the TLS context and configure a single custom extension (no callback). Expected result 1. * 2. Prepare a buffer containing a single extension and call the ParseCustomExtensions interface. Expected result 2. * @expect * 1. Initialization successful. * 2. Returns HITLS_SUCCESS, buffer offset is updated correctly. @ */ /* BEGIN_CASE */ void SDV_TLS_PARSE_CUSTOM_EXTENSIONS_API_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_NE(tlsConfig, NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_NE(ctx, NULL); uint8_t buf[1024] = {0xAA}; // ext_type=1, len=0 uint32_t bufOffset = 0; uint16_t extType = CUSTOM_EXTENTIONS_TYPE_1; uint32_t context = 1; uint32_t extLen = 1; // Configure a single custom extension CustomExtMethods exts = {0}; CustomExtMethod meth = {0}; meth.extType = extType; meth.parseCb = NULL; // No callback exts.meths = &meth; exts.methsCount = 1; ctx->config.tlsConfig.customExts = &exts; // Call the interface under test int32_t ret = ParseCustomExtensions(ctx, buf + bufOffset, extType, extLen, context, NULL, 0); ctx->config.tlsConfig.customExts = NULL; ASSERT_EQ(ret, HITLS_SUCCESS); // Verify the return value is success // Note: Current implementation doesn't update bufOffset without parse_cb, adjust expectation if needed EXIT: HITLS_Free(ctx); HITLS_CFG_FreeConfig(tlsConfig); return; } /* END_CASE */ /** @ * @test SDV_TLS_PACK_CUSTOM_EXTENSIONS_MULTIPLE_API_TC001 * @title Test the multiple extensions packing function of the PackCustomExtensions interface * @precon None * @brief * 1. Initialize the TLS context and configure two custom extensions. Expected result 1. * 2. Call the PackCustomExtensions interface and verify the packing result. Expected result 2. * @expect * 1. Initialization successful. * 2. Returns HITLS_SUCCESS, packing length is 0 (no data without callbacks). @ */ /* BEGIN_CASE */ void SDV_TLS_PACK_CUSTOM_EXTENSIONS_MULTIPLE_API_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_NE(tlsConfig, NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_NE(ctx, NULL); uint8_t buf[1024] = {0}; uint32_t bufLen = sizeof(buf); uint32_t len = 0; uint32_t context = 1; uint32_t methsCount = 1; // Configure multiple custom extensions CustomExtMethods exts = {0}; CustomExtMethod meths[2] = {{0}, {0}}; meths[0].extType = CUSTOM_EXTENTIONS_TYPE_1; meths[0].context = context; meths[0].addCb = NULL; // No callback meths[0].freeCb = NULL; meths[1].extType = CUSTOM_EXTENTIONS_TYPE_2; meths[1].context = context; meths[1].addCb = NULL; // No callback meths[1].freeCb = NULL; exts.meths = meths; exts.methsCount = methsCount; ctx->config.tlsConfig.customExts = &exts; uint32_t bufOffset = 0; uint8_t *buffAddr = &buf[0]; PackPacket pkt = {.buf = &buffAddr, .bufLen = &bufLen, .bufOffset = &bufOffset}; // Call the interface under test int32_t ret = PackCustomExtensions(ctx, &pkt, context, NULL, 0); ctx->config.tlsConfig.customExts = NULL; ASSERT_EQ(ret, HITLS_SUCCESS); // Verify the return value is success ASSERT_EQ(len, 0); // No data packed without add_cb EXIT: HITLS_Free(ctx); HITLS_CFG_FreeConfig(tlsConfig); return; } /* END_CASE */ /** @ * @test SDV_TLS_PACK_CUSTOM_EXTENSIONS_EMPTY_API_TC001 * @title Test the behavior of the PackCustomExtensions interface when there are no extensions * @precon None * @brief * 1. Initialize the TLS context without configuring any custom extensions. Expected result 1. * 2. Call the PackCustomExtensions interface and verify the packing result. Expected result 2. * @expect * 1. Initialization successful. * 2. Returns HITLS_SUCCESS, packing length is 0. @ */ /* BEGIN_CASE */ void SDV_TLS_PACK_CUSTOM_EXTENSIONS_EMPTY_API_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_NE(tlsConfig, NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_NE(ctx, NULL); uint8_t buf[1024] = {0}; uint32_t bufLen = sizeof(buf); uint32_t len = 0; uint32_t context = 1; ctx->config.tlsConfig.customExts = NULL; // No extensions uint32_t bufOffset = 0; uint8_t *buffAddr = &buf[0]; PackPacket pkt = {.buf = &buffAddr, .bufLen = &bufLen, .bufOffset = &bufOffset}; // Call the interface under test int32_t ret = PackCustomExtensions(ctx, &pkt, context, NULL, 0); ASSERT_EQ(ret, HITLS_SUCCESS); // Verify the return value is success ASSERT_EQ(len, 0); // Verify the packing length is 0 EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); return; } /* END_CASE */ /** @ * @test SDV_TLS_PACK_CUSTOM_EXTENSIONS_CALLBACK_API_TC001 * @title Test the PackCustomExtensions interface with callbacks * @precon None * @brief * 1. Initialize the TLS context and configure a single custom extension with add_cb and free_cb. Expected result 1. * 2. Call the PackCustomExtensions interface and verify the packing result. Expected result 2. * @expect * 1. Initialization successful. * 2. Returns HITLS_SUCCESS, packing length is 3 (ext_type + data), buffer content is correct. @ */ /* BEGIN_CASE */ void SDV_TLS_PACK_CUSTOM_EXTENSIONS_CALLBACK_API_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_NE(ctx, NULL); uint8_t buf[1024] = {0}; uint32_t bufLen = sizeof(buf); uint32_t len = 0; uint16_t extType = CUSTOM_EXTENTIONS_TYPE_1; uint32_t context = 1; uint32_t dataLen = 1; // Configure a single custom extension with callbacks CustomExtMethods exts = {0}; CustomExtMethod meth = {0}; meth.extType = extType; meth.context = context; meth.addCb = SimpleAddCb; meth.freeCb = SimpleFreeCb; exts.meths = &meth; exts.methsCount = 1; ctx->config.tlsConfig.customExts = &exts; uint32_t bufOffset = 0; uint8_t *buffAddr = &buf[0]; PackPacket pkt = {.buf = &buffAddr, .bufLen = &bufLen, .bufOffset = &bufOffset}; // Call the interface under test int32_t ret = PackCustomExtensions(ctx, &pkt, context, NULL, 0); ctx->config.tlsConfig.customExts = NULL; ASSERT_EQ(ret, HITLS_SUCCESS); // Verify the return value is success len += bufOffset; ASSERT_EQ(len, sizeof(uint16_t) + sizeof(uint16_t) + dataLen); // ext_type (2 byte) + len (2 byte) + data (1 byte) // Verify the extension type uint16_t packedType = BSL_ByteToUint16(buf); ASSERT_EQ(packedType, extType); uint16_t packedLen = BSL_ByteToUint16(&buf[sizeof(uint16_t)]); ASSERT_EQ(packedLen, 1); // Verify the len ASSERT_EQ(buf[len - 1], 0xAA); // Verify the data EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); return; } /* END_CASE */ /** @ * @test SDV_TLS_PARSE_CUSTOM_EXTENSIONS_CALLBACK_API_TC001 * @title Test the ParseCustomExtensions interface with parse_cb * @precon None * @brief * 1. Initialize the TLS context and configure a single custom extension with parse_cb. Expected result 1. * 2. Prepare a buffer containing a single extension and call the ParseCustomExtensions interface. Expected result 2. * @expect * 1. Initialization successful. * 2. Returns HITLS_SUCCESS, buffer offset is updated correctly. @ */ /* BEGIN_CASE */ void SDV_TLS_PARSE_CUSTOM_EXTENSIONS_CALLBACK_API_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_NE(tlsConfig, NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_NE(ctx, NULL); uint8_t buf[1024] = {0xAA}; // ext_type=1 (big-endian), len=1, data=0xAA uint32_t bufOffset = 0; uint16_t extType = CUSTOM_EXTENTIONS_TYPE_1; uint32_t context = 1; uint32_t extLen = 1; // Configure a single custom extension with parse callback CustomExtMethods exts = {0}; CustomExtMethod meth = {0}; meth.extType = extType; meth.context = context; meth.parseCb = SimpleParseCb; exts.meths = &meth; exts.methsCount = 1; ctx->config.tlsConfig.customExts = &exts; // Call the interface under test int32_t ret = ParseCustomExtensions(ctx, buf + bufOffset, extType, extLen, context, NULL, 0); ctx->config.tlsConfig.customExts = NULL; ASSERT_EQ(ret, HITLS_SUCCESS); // Verify the return value is success EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); return; } /* END_CASE */ /** @ * @test SDV_TLS_SSLCTX_ADD_CUSTOM_EXTENSION_API_TC002 * @title Test the custom extension addition functionality of the HITLS_AddCustomExtension function * @precon None * @brief * 1. Initialize the TLS context and add a valid custom extension, verify if the addition is successful. * Expected result 1. * 2. Attempt to add a duplicate custom extension, verify if the function rejects the duplicate addition. * Expected result 2. * 3. Call the function with invalid parameters (add_cb is NULL, free_cb is not NULL), verify if the function correctly * handles the error. Expected result 3. * @expect * 1. Returns HITLS_SUCCESS, the custom extension is correctly added to the context. * 2. Returns 0, the number of extensions does not increase. * 3. Returns 0, the number of extensions does not increase. @ */ /* BEGIN_CASE */ void SDV_HITLS_ADD_CUSTOM_EXTENSION_API_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *tlsConfig = HITLS_CFG_NewTLS13Config(); ASSERT_NE(tlsConfig, NULL); uint16_t extType = CUSTOM_EXTENTIONS_TYPE_1; uint16_t invalidExtType = CUSTOM_EXTENTIONS_TYPE_2; uint32_t context = 1; HITLS_AddCustomExtCallback addCb = SimpleAddCb; HITLS_FreeCustomExtCallback freeCb = SimpleFreeCb; void *addArg = NULL; HITLS_ParseCustomExtCallback parseCb = SimpleParseCb; void *parseArg = NULL; // Test normal case: Add a custom extension HITLS_CustomExtParams params = { .extType = extType, .context = context, .addCb = addCb, .freeCb = freeCb, .addArg = addArg, .parseCb = parseCb, .parseArg = parseArg }; uint32_t ret = HITLS_CFG_AddCustomExtension(tlsConfig, &params); ASSERT_EQ(ret, HITLS_SUCCESS); // Verify the return value is success ASSERT_EQ(tlsConfig->customExts->methsCount, 1); // Verify the number of extensions is 1 CustomExtMethod *meth = &tlsConfig->customExts->meths[0]; ASSERT_EQ(meth->extType, extType); // Verify the extension type ASSERT_EQ(meth->context, context); // Verify the context ASSERT_EQ(meth->addCb, addCb); // Verify add_cb ASSERT_EQ(meth->freeCb, freeCb); // Verify free_cb ASSERT_EQ(meth->addArg, addArg); // Verify add_arg ASSERT_EQ(meth->parseCb, parseCb); // Verify parse_cb ASSERT_EQ(meth->parseArg, parseArg); // Verify parse_arg // Test boundary case: Attempt to add a duplicate extension HITLS_CustomExtParams duplicateParams = { .extType = extType, .context = context, .addCb = addCb, .freeCb = freeCb, .addArg = addArg, .parseCb = parseCb, .parseArg = parseArg }; ret = HITLS_CFG_AddCustomExtension(tlsConfig, &duplicateParams); ASSERT_EQ(ret, HITLS_CONFIG_DUP_CUSTOM_EXT); // Verify the return value is failure ASSERT_EQ(tlsConfig->customExts->methsCount, 1); // Verify the number of extensions does not increase // Test invalid parameters: add_cb is NULL, free_cb is not NULL HITLS_CustomExtParams invalidParams = { .extType = invalidExtType, .context = context, .addCb = NULL, .freeCb = freeCb, .addArg = addArg, .parseCb = parseCb, .parseArg = parseArg }; ret = HITLS_CFG_AddCustomExtension(tlsConfig, &invalidParams); ASSERT_EQ(ret, HITLS_INVALID_INPUT); // Verify the return value is failure ASSERT_EQ(tlsConfig->customExts->methsCount, 1); // Verify the number of extensions does not increase EXIT: HITLS_CFG_FreeConfig(tlsConfig); return; } /* END_CASE */ typedef struct { uint32_t parsedContext[10]; uint32_t parsedContextCount; uint32_t addedContext[10]; uint32_t addedContextCount; uint32_t alertContext; uint32_t alert; bool addEmptyExt; bool parseEmptyExt; bool passExt; } CustomExtensionArg; int CustomExtensionAddCb(const struct TlsCtx *ctx, uint16_t extType, uint32_t context, uint8_t **out, uint32_t *outLen, HITLS_CERT_X509 *cert, uint32_t certId, uint32_t *alert, void *addArg) { (void)ctx; (void)extType; (void)cert; (void)certId; (void)alert; CustomExtensionArg *arg = (CustomExtensionArg *)addArg; arg->addedContext[arg->addedContextCount++] = context; if ((arg->alertContext & context) != 0) { *alert = arg->alert; return -1; } if (arg->passExt) { *out = NULL; *outLen = 0; return HITLS_ADD_CUSTOM_EXTENSION_RET_PASS; } if (arg->addEmptyExt) { *out = NULL; *outLen = 0; return HITLS_ADD_CUSTOM_EXTENSION_RET_PACK; } *out = malloc(1); if (*out == NULL) { return -1; } *outLen = 1; (*out)[0] = 0xAA; return HITLS_ADD_CUSTOM_EXTENSION_RET_PACK; } // Simple free_cb function, frees the allocated data void CustomExtensionFreeCb(const struct TlsCtx *ctx, uint16_t extType, uint32_t context, uint8_t *out, void *addArg) { (void)ctx; (void)extType; (void)context; (void)addArg; BSL_SAL_Free(out); } // Simple parse_cb function, reads the length and data, checks the data int CustomExtensionParseCb(const struct TlsCtx *ctx, uint16_t extType, uint32_t context, const uint8_t **in, uint32_t *inLen, HITLS_CERT_X509 *cert, uint32_t certId, uint32_t *alert, void *parseArg) { (void)ctx; (void)extType; (void)context; (void)cert; (void)certId; (void)alert; CustomExtensionArg *arg = (CustomExtensionArg *)parseArg; arg->parsedContext[arg->parsedContextCount++] = context; if ((arg->alertContext & context) != 0) { *alert = arg->alert; return -1; } if (arg->parseEmptyExt) { if (*inLen > 0) { return -1; } return 0; } if (arg->passExt) { return -1; } if (*inLen != 1 || (*in)[0] != 0xAA) { return -1; } return 0; } /** * @test SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC001 * @title Basic Functionality Test for Custom Extensions */ /* BEGIN_CASE */ void SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC001(void) { FRAME_Init(); // Initialize the test framework HITLS_Config *clientConfig = HITLS_CFG_NewTLS13Config(); HITLS_Config *serverConfig = HITLS_CFG_NewTLS13Config(); HITLS_CFG_SetClientVerifySupport(serverConfig, true); CustomExtensionArg serverArg = {0}; CustomExtensionArg clientArg = {0}; HITLS_CustomExtParams params = { .extType = CUSTOM_EXTENTIONS_TYPE_2, .context = HITLS_EX_TYPE_CLIENT_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO | HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS | HITLS_EX_TYPE_TLS1_3_CERTIFICATE | HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST | HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET, .addCb = CustomExtensionAddCb, .freeCb = CustomExtensionFreeCb, .addArg = &clientArg, .parseCb = CustomExtensionParseCb, .parseArg = &clientArg }; HITLS_CFG_AddCustomExtension(clientConfig, &params); params.addArg = &serverArg; params.parseArg = &serverArg; HITLS_CFG_AddCustomExtension(serverConfig, &params); FRAME_LinkObj *client = FRAME_CreateLink(clientConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(serverConfig, BSL_UIO_TCP); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_EQ(clientArg.addedContextCount, 3); ASSERT_EQ(clientArg.parsedContextCount, 7); ASSERT_EQ(clientArg.addedContext[0], HITLS_EX_TYPE_CLIENT_HELLO); ASSERT_EQ(clientArg.addedContext[1], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(clientArg.addedContext[2], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(clientArg.parsedContext[0], HITLS_EX_TYPE_TLS1_2_SERVER_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO | HITLS_EX_TYPE_HELLO_RETRY_REQUEST); ASSERT_EQ(clientArg.parsedContext[1], HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS); ASSERT_EQ(clientArg.parsedContext[2], HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST); ASSERT_EQ(clientArg.parsedContext[3], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(clientArg.parsedContext[4], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(clientArg.parsedContext[5], HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET); ASSERT_EQ(clientArg.parsedContext[6], HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET); ASSERT_EQ(serverArg.addedContextCount, 7); ASSERT_EQ(serverArg.parsedContextCount, 3); ASSERT_EQ(serverArg.parsedContext[0], HITLS_EX_TYPE_CLIENT_HELLO); ASSERT_EQ(serverArg.parsedContext[1], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(serverArg.parsedContext[2], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(serverArg.addedContext[0], HITLS_EX_TYPE_TLS1_3_SERVER_HELLO); ASSERT_EQ(serverArg.addedContext[1], HITLS_EX_TYPE_ENCRYPTED_EXTENSIONS); ASSERT_EQ(serverArg.addedContext[2], HITLS_EX_TYPE_TLS1_3_CERTIFICATE_REQUEST); ASSERT_EQ(serverArg.addedContext[3], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(serverArg.addedContext[4], HITLS_EX_TYPE_TLS1_3_CERTIFICATE); ASSERT_EQ(serverArg.addedContext[5], HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET); ASSERT_EQ(serverArg.addedContext[5], HITLS_EX_TYPE_TLS1_3_NEW_SESSION_TICKET); EXIT: HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC002 * @title Alert Scenario Test for Custom Extensions */ /* BEGIN_CASE */ void SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC002() { FRAME_Init(); // Initialize the test framework HITLS_Config *clientConfig = HITLS_CFG_NewTLS13Config(); HITLS_Config *serverConfig = HITLS_CFG_NewTLS13Config(); CustomExtensionArg serverArg = {0}; CustomExtensionArg clientArg = {0}; clientArg.alert = ALERT_ILLEGAL_PARAMETER; clientArg.alertContext = HITLS_EX_TYPE_TLS1_3_SERVER_HELLO; HITLS_CustomExtParams params = { .extType = CUSTOM_EXTENTIONS_TYPE_2, .context = HITLS_EX_TYPE_CLIENT_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO, .addCb = CustomExtensionAddCb, .freeCb = CustomExtensionFreeCb, .addArg = &clientArg, .parseCb = CustomExtensionParseCb, .parseArg = &clientArg }; HITLS_CFG_AddCustomExtension(clientConfig, &params); params.addArg = &serverArg; params.parseArg = &serverArg; HITLS_CFG_AddCustomExtension(serverConfig, &params); FRAME_LinkObj *client = FRAME_CreateLink(clientConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(serverConfig, BSL_UIO_TCP); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), -1); ALERT_Info info = {0}; ALERT_GetInfo(client->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_ILLEGAL_PARAMETER); EXIT: HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC003 * @title Empty Extension Capability Test */ /* BEGIN_CASE */ void SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC003() { FRAME_Init(); // Initialize the test framework HITLS_Config *clientConfig = HITLS_CFG_NewTLS13Config(); HITLS_Config *serverConfig = HITLS_CFG_NewTLS13Config(); CustomExtensionArg serverArg = {0}; CustomExtensionArg clientArg = {0}; clientArg.addEmptyExt = true; clientArg.parseEmptyExt = false; serverArg.addEmptyExt = false; serverArg.parseEmptyExt = true; HITLS_CustomExtParams params = { .extType = CUSTOM_EXTENTIONS_TYPE_2, .context = HITLS_EX_TYPE_CLIENT_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO, .addCb = CustomExtensionAddCb, .freeCb = CustomExtensionFreeCb, .addArg = &clientArg, .parseCb = CustomExtensionParseCb, .parseArg = &clientArg }; HITLS_CFG_AddCustomExtension(clientConfig, &params); params.addArg = &serverArg; params.parseArg = &serverArg; HITLS_CFG_AddCustomExtension(serverConfig, &params); FRAME_LinkObj *client = FRAME_CreateLink(clientConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(serverConfig, BSL_UIO_TCP); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), 0); ASSERT_EQ(clientArg.addedContextCount, 1); ASSERT_EQ(clientArg.parsedContextCount, 1); ASSERT_EQ(clientArg.addedContext[0], HITLS_EX_TYPE_CLIENT_HELLO); ASSERT_EQ(clientArg.parsedContext[0], HITLS_EX_TYPE_TLS1_2_SERVER_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO | HITLS_EX_TYPE_HELLO_RETRY_REQUEST); ASSERT_EQ(serverArg.addedContextCount, 1); ASSERT_EQ(serverArg.parsedContextCount, 1); ASSERT_EQ(serverArg.addedContext[0], HITLS_EX_TYPE_TLS1_3_SERVER_HELLO); ASSERT_EQ(serverArg.parsedContext[0], HITLS_EX_TYPE_CLIENT_HELLO); EXIT: HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC004 * @title Pass Extension Capability Test */ /* BEGIN_CASE */ void SDV_HITLS_CUSTOM_EXTENSION_FUNCTION_TC004() { FRAME_Init(); // Initialize the test framework HITLS_Config *clientConfig = HITLS_CFG_NewTLS13Config(); HITLS_Config *serverConfig = HITLS_CFG_NewTLS13Config(); CustomExtensionArg serverArg = {0}; CustomExtensionArg clientArg = {0}; clientArg.passExt = true; serverArg.passExt = true; HITLS_CustomExtParams params = { .extType = CUSTOM_EXTENTIONS_TYPE_2, .context = HITLS_EX_TYPE_CLIENT_HELLO | HITLS_EX_TYPE_TLS1_3_SERVER_HELLO, .addCb = CustomExtensionAddCb, .freeCb = CustomExtensionFreeCb, .addArg = &clientArg, .parseCb = CustomExtensionParseCb, .parseArg = &clientArg }; HITLS_CFG_AddCustomExtension(clientConfig, &params); params.addArg = &serverArg; params.parseArg = &serverArg; HITLS_CFG_AddCustomExtension(serverConfig, &params); FRAME_LinkObj *client = FRAME_CreateLink(clientConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(serverConfig, BSL_UIO_TCP); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), 0); ASSERT_EQ(clientArg.addedContextCount, 1); ASSERT_EQ(clientArg.parsedContextCount, 0); ASSERT_EQ(serverArg.addedContextCount, 1); ASSERT_EQ(serverArg.parsedContextCount, 0); EXIT: HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/custom/test_suite_sdv_custom_extensions.c
C
unknown
28,516
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_BASE ../consistency/tls12/test_suite_tls12_consistency_rfc5246_malformed_msg */ /* BEGIN_HEADER */ #include "securec.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "stub_replace.h" #include "hitls_error.h" #include "tls.h" #include "bsl_uio.h" #include "rec.h" #include "crypt.h" #include "rec_conn.h" #include "record.h" #include "bsl_uio.h" #include "hitls.h" #include "frame_tls.h" #include "cert_callback.h" /* END_HEADER */ /* UserData structure transferred from the server to the alpnCb callback */ static uint8_t S_parsedList[100]; static uint32_t S_parsedListLen; static TlsAlpnExtCtx alpnServerCtx = {0}; static uint8_t C_parsedList[100]; static uint32_t C_parsedListLen; static int32_t ConfigAlpn(HITLS_Config *tlsConfig, char *AlpnList, bool isCient) { int32_t ret; char defaultAlpnList[] = "http/1.1,spdy/1,spdy/2,spdy/3"; char *pAlpnList = NULL; uint32_t AlpnListLen = 0; if (AlpnList != NULL){ pAlpnList = AlpnList; AlpnListLen = strlen(pAlpnList); } else { pAlpnList = defaultAlpnList; AlpnListLen = strlen(pAlpnList); } /* client set alpn */ if (isCient) { ret = ExampleAlpnParseProtocolList(C_parsedList, &C_parsedListLen, (uint8_t *)pAlpnList, AlpnListLen); ASSERT_EQ(ret, HITLS_SUCCESS); ret = HITLS_CFG_SetAlpnProtos(tlsConfig, C_parsedList, C_parsedListLen); ASSERT_EQ(ret, HITLS_SUCCESS); /* server set alpn and alpnSelectCb */ } else { ret = ExampleAlpnParseProtocolList(S_parsedList, &S_parsedListLen, (uint8_t *)pAlpnList, AlpnListLen); ASSERT_EQ(ret, HITLS_SUCCESS); alpnServerCtx = (TlsAlpnExtCtx){ S_parsedList, S_parsedListLen }; ret = HITLS_CFG_SetAlpnProtosSelectCb(tlsConfig, ExampleAlpnCbForLlt, &alpnServerCtx); ASSERT_EQ(ret, HITLS_SUCCESS); } EXIT: return ret; } /** * @test UT_TLS_ALPN_PARSE_PROTO_FUNC_TC001 * @title ALPN function test * @precon nan * @brief server set alpn and alpn callback,client set alpn. The server supports the protocol configured on the client .Expect result 1 * @expect 1. server returns the protocol supported by the client */ /* BEGIN_CASE */ void UT_TLS_ALPN_PARSE_PROTO_FUNC_TC001(int version) { FRAME_Init(); RegDefaultMemCallback(); HITLS_Config *s_config = NULL; HITLS_Config *c_config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; if (version == HITLS_VERSION_TLS12) { c_config = HITLS_CFG_NewTLS12Config(); s_config = HITLS_CFG_NewTLS12Config(); } else if (version == HITLS_VERSION_TLS13) { c_config = HITLS_CFG_NewTLS13Config(); s_config = HITLS_CFG_NewTLS13Config(); } ASSERT_TRUE(c_config != NULL); ASSERT_TRUE(s_config != NULL); uint16_t groups[] = {HITLS_EC_GROUP_SECP256R1}; uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetGroups(c_config, groups, sizeof(groups) / sizeof(uint16_t)); HITLS_CFG_SetSignature(c_config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); HITLS_CFG_SetGroups(s_config, groups, sizeof(groups) / sizeof(uint16_t)); HITLS_CFG_SetSignature(s_config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); ConfigAlpn(s_config, NULL, false); ConfigAlpn(c_config, NULL, true); client = FRAME_CreateLink(c_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); int32_t ret; ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_SUCCESS); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(memcmp(clientTlsCtx->negotiatedInfo.alpnSelected, "http/1.1", 8) == 0); ASSERT_TRUE(clientTlsCtx->negotiatedInfo.alpnSelectedSize == 8); ASSERT_TRUE(memcmp(serverTlsCtx->negotiatedInfo.alpnSelected, "http/1.1", 8) == 0); ASSERT_TRUE(serverTlsCtx->negotiatedInfo.alpnSelectedSize == 8); EXIT: HITLS_CFG_FreeConfig(s_config); HITLS_CFG_FreeConfig(c_config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_alpn_interface.c
C
unknown
4,793
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <sys/types.h> #include <regex.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/select.h> #include <sys/time.h> #include <linux/ioctl.h> #include "securec.h" #include "bsl_sal.h" #include "sal_net.h" #include "frame_tls.h" #include "cert_callback.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "frame_io.h" #include "uio_abstraction.h" #include "tls.h" #include "tls_config.h" #include "logger.h" #include "process.h" #include "hs_ctx.h" #include "hlt.h" #include "stub_replace.h" #include "hitls_type.h" #include "frame_link.h" #include "session_type.h" #include "common_func.h" #include "hitls_func.h" #include "hitls_cert_type.h" #include "cert_mgr_ctx.h" #include "parser_frame_msg.h" #include "recv_process.h" #include "simulate_io.h" #include "rec_wrapper.h" #include "cipher_suite.h" #include "alert.h" #include "conn_init.h" #include "pack.h" #include "send_process.h" #include "cert.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "hs.h" #include "hs_state_recv.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "frame_msg.h" #include "pack_frame_msg.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "sctp_channel.h" #include "hitls_crypt_init.h" #include "hitls_session.h" #include "bsl_log.h" #include "bsl_err.h" #include "hitls_crypt_reg.h" #include "crypt_errno.h" #include "bsl_list.h" #include "hitls_cert.h" #include "parse_extensions_client.c" #include "parse_extensions_server.c" #include "parse_server_hello.c" #include "parse_client_hello.c" #include "uio_udp.c" /* END_HEADER */ /** @ * @test UT_TLS_CFG_SET_GET_REC_INBUFFER_SIZE_API_TC001 * @title Test the HITLS_CFG_SetRecInbufferSize and HITLS_CFG_GetRecInbufferSize. * @precon nan * @brief HITLS_CFG_SetRecInbufferSize * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set recInbufferSize to an invalid value. Expected result 2. * 3. Transfer a non-empty TLS connection handle information and set recInbufferSize to a valid value. Expected result 3 * HITLS_CFG_GetRecInbufferSize * 1. Input an empty TLS connection handle or NULL recInbufferSize pointer. Expected result 1. * 2. Transfer a non-empty TLS connection handle and recInbufferSize pointer.Expected result 3. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_CONFIG_INVALID_LENGTH is returned * 3. Returns HITLS_SUCCES. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_REC_INBUFFER_SIZE_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; config = HITLS_CFG_NewTLS12Config(); uint32_t recInbufferSize = 18433; ASSERT_TRUE(HITLS_CFG_SetRecInbufferSize(NULL, recInbufferSize) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetRecInbufferSize(config, recInbufferSize) == HITLS_CONFIG_INVALID_LENGTH); /* value < 512 */ recInbufferSize = 511; ASSERT_TRUE(HITLS_CFG_SetRecInbufferSize(config, recInbufferSize) == HITLS_CONFIG_INVALID_LENGTH); /* 18432 > value > 512 */ recInbufferSize = 1000; ASSERT_TRUE(HITLS_CFG_SetRecInbufferSize(config, recInbufferSize) == HITLS_SUCCESS); uint32_t recInbufferSize2 = 0; ASSERT_TRUE(HITLS_CFG_GetRecInbufferSize(NULL, &recInbufferSize2) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetRecInbufferSize(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetRecInbufferSize(config, &recInbufferSize2) == HITLS_SUCCESS); ASSERT_EQ(recInbufferSize2, 1000); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_GET_REC_INBUFFER_SIZE_API_TC001 * @title Test the HITLS_SetRecInbufferSize and HITLS_GetRecInbufferSize. * @precon nan * @brief HITLS_SetRecInbufferSize * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set recInbufferSize to an invalid value. Expected result 2. * 3. Transfer a non-empty TLS connection handle information and set recInbufferSize to a valid value. Expected result 3 * HITLS_GetRecInbufferSize * 1. Input an empty TLS connection handle or NULL recInbufferSize pointer. Expected result 1. * 2. Transfer a non-empty TLS connection handle and recInbufferSize pointer.Expected result 3. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_CONFIG_INVALID_LENGTH is returned * 3. Returns HITLS_SUCCES. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_REC_INBUFFER_SIZE_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; config = HITLS_CFG_NewDTLS12Config(); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); /* value > 18432 */ uint32_t recInbufferSize = 18433; ASSERT_TRUE(HITLS_SetRecInbufferSize(NULL, recInbufferSize) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetRecInbufferSize(ctx, recInbufferSize) == HITLS_CONFIG_INVALID_LENGTH); /* value < 512 */ recInbufferSize = 511; ASSERT_TRUE(HITLS_SetRecInbufferSize(ctx, recInbufferSize) == HITLS_CONFIG_INVALID_LENGTH); /* 18432 > value > 512 */ recInbufferSize = 1000; ASSERT_TRUE(HITLS_SetRecInbufferSize(ctx, recInbufferSize) == HITLS_SUCCESS); uint32_t recInbufferSize2 = 0; ASSERT_TRUE(HITLS_GetRecInbufferSize(NULL, &recInbufferSize2) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetRecInbufferSize(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetRecInbufferSize(ctx, &recInbufferSize2) == HITLS_SUCCESS); ASSERT_EQ(recInbufferSize2, 1000); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_buffer_minimization.c
C
unknown
6,441
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "hlt.h" #include "logger.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "crypt_util_rand.h" #include "helper.h" #include "hitls.h" #include "frame_tls.h" #include "frame_link.h" #include "hitls_type.h" #include "rec_wrapper.h" #include "hs_ctx.h" #include "tls.h" #include "hitls_config.h" #include "alert.h" #include "hitls_func.h" /* END_HEADER */ static void CaListNodeInnerDestroy(void *data) { HITLS_TrustedCANode *tmpData = (HITLS_TrustedCANode *)data; BSL_SAL_FREE(tmpData->data); BSL_SAL_FREE(tmpData); return; } /** * @test UT_TLS_TLS13_RECV_CA_LIST_TC001 * @brief 1. Use the default configuration items to configure the client and server, Expect result 1. * 2. Load the CA file into the configuration, Expect result 1. * 3. Set the CA list in the configuration, Expect result 1. * 4. Create the client and server links, Expect result 2. * @expect 1. HITLS_SUCCESS * 2. caList->count == 1 */ /* BEGIN_CASE */ void UT_TLS_CERT_CFG_LoadCAFile_API_TC001(int version, char *certFile, char *userdata) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); HITLS_TrustedCAList *caList = NULL; ASSERT_TRUE(HITLS_CFG_SetDefaultPasswordCbUserdata(tlsConfig, userdata) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetDefaultPasswordCbUserdata(tlsConfig) == userdata); ASSERT_TRUE(HITLS_CFG_ParseCAList(tlsConfig, certFile, (uint32_t)strlen(certFile), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1, &caList) == HITLS_SUCCESS); ASSERT_TRUE(caList != NULL); ASSERT_TRUE(caList->count == 1); EXIT: HITLS_CFG_FreeConfig(tlsConfig); BSL_LIST_FREE(caList, CaListNodeInnerDestroy); } /* END_CASE */ /** @ * @test UT_TLS_TLS13_RECV_CA_LIST_TC001 * @spec - * @title The CA list is parsed correctly. * @precon nan * @brief 1. Use the default configuration items to configure the client and server, Expect result 1. * 2. Load the CA file into the configuration, Expect result 1. * 3. Set the CA list in the configuration, Expect result 1. * 4. Create the client and server links, Expect result 1. * 5. Create the connection between the client and server, Expect result 2. * 6. Get the peer CA list from the server, Expect result 1. * 7. Verify that the peer CA list is not NULL and contains one CA, Expect result 3. * @expect 1. HITLS_SUCCESS * 2. link established successfully * 3. peerList != NULL @ */ /* BEGIN_CASE */ void UT_TLS_TLS13_RECV_CA_LIST_TC001(char *certFile) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); HITLS_TrustedCAList *caList = NULL; ASSERT_TRUE(HITLS_CFG_ParseCAList(config, certFile, (uint32_t)strlen(certFile), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1, &caList) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCAList(config, caList) == HITLS_SUCCESS); ASSERT_TRUE(caList != NULL); ASSERT_TRUE(caList->count == 1); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_TrustedCAList *peerList = HITLS_GetPeerCAList(server->ssl); ASSERT_TRUE(peerList != NULL); ASSERT_TRUE(peerList->count == 1); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_TLS12_RECV_CA_LIST_TC001 * @spec - * @title The CA list is parsed correctly. * @precon nan * @brief 1. Use the default configuration items to configure the client and server, Expect result 1. * 2. Load the CA file into the configuration, Expect result 1. * 3. Set the CA list in the configuration, Expect result 1. * 4. set ClientVerifySupport, Expect result 1. * 4. Create the client and server links, Expect result 1. * 5. Create the connection between the client and server, Expect result 2. * 6. Get the peer CA list from the server, Expect result 1. * 7. Verify that the peer CA list is not NULL and contains one CA, Expect result 3. * @expect 1. HITLS_SUCCESS * 2. link established successfully * 3. peerList != NULL @ */ /* BEGIN_CASE */ void UT_TLS_TLS12_RECV_CA_LIST_TC001(char *certFile) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_TrustedCAList *caList = NULL; ASSERT_TRUE(HITLS_CFG_ParseCAList(config, certFile, (uint32_t)strlen(certFile), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1, &caList) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCAList(config, caList) == HITLS_SUCCESS); HITLS_CFG_SetClientVerifySupport(config, true); ASSERT_TRUE(caList != NULL); ASSERT_TRUE(caList->count == 1); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_TrustedCAList *peerList = HITLS_GetPeerCAList(client->ssl); ASSERT_TRUE(peerList != NULL); ASSERT_TRUE(peerList->count == 1); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_ca_list.c
C
unknown
6,453
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <sys/types.h> #include <regex.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/select.h> #include <sys/time.h> #include <linux/ioctl.h> #include "securec.h" #include "bsl_sal.h" #include "sal_net.h" #include "frame_tls.h" #include "cert_callback.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "frame_io.h" #include "uio_abstraction.h" #include "tls.h" #include "tls_config.h" #include "logger.h" #include "process.h" #include "hs_ctx.h" #include "hlt.h" #include "stub_replace.h" #include "hitls_type.h" #include "frame_link.h" #include "session_type.h" #include "common_func.h" #include "hitls_func.h" #include "hitls_cert_type.h" #include "cert_mgr_ctx.h" #include "parser_frame_msg.h" #include "recv_process.h" #include "simulate_io.h" #include "rec_wrapper.h" #include "cipher_suite.h" #include "alert.h" #include "conn_init.h" #include "pack.h" #include "send_process.h" #include "cert.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "hs.h" #include "hs_state_recv.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "frame_msg.h" #include "pack_frame_msg.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "sctp_channel.h" #include "hitls_crypt_init.h" #include "hitls_session.h" #include "bsl_log.h" #include "bsl_err.h" #include "hitls_crypt_reg.h" #include "crypt_errno.h" #include "bsl_list.h" #include "hitls_cert.h" #include "parse_extensions_client.c" #include "parse_extensions_server.c" #include "parse_server_hello.c" #include "parse_client_hello.c" #include "uio_udp.c" /* END_HEADER */ /** @ * @test UT_TLS_CFG_SET_GET_MAX_SEND_FRAGMENT_API_TC001 * @title Test the HITLS_CFG_SetMaxSendFragment and HITLS_CFG_GetMaxSendFragment. * @precon nan * @brief HITLS_CFG_SetMaxSendFragment * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set maxSendFragment to an invalid value. Expected result 2. * 3. Transfer a non-empty TLS connection handle information and set maxSendFragment to a valid value. Expected result 3 * HITLS_CFG_GetMaxSendFragment * 1. Input an empty TLS connection handle or NULL maxSendFragment pointer. Expected result 1. * 2. Transfer a non-empty TLS connection handle and maxSendFragment pointer.Expected result 3. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_CONFIG_INVALID_LENGTH is returned * 3. Returns HITLS_SUCCES. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_MAX_SEND_FRAGMENT_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; config = HITLS_CFG_NewDTLS12Config(); uint16_t maxSendFragment = 16385; ASSERT_TRUE(HITLS_CFG_SetMaxSendFragment(NULL, maxSendFragment) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetMaxSendFragment(config, maxSendFragment) == HITLS_CONFIG_INVALID_LENGTH); /* value < 512 */ maxSendFragment = 511; ASSERT_TRUE(HITLS_CFG_SetMaxSendFragment(config, maxSendFragment) == HITLS_CONFIG_INVALID_LENGTH); /* 16384 > value > 512 */ maxSendFragment = 1000; ASSERT_TRUE(HITLS_CFG_SetMaxSendFragment(config, maxSendFragment) == HITLS_SUCCESS); uint16_t maxSendFragment2 = 0; ASSERT_TRUE(HITLS_CFG_GetMaxSendFragment(NULL, &maxSendFragment2) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMaxSendFragment(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMaxSendFragment(config, &maxSendFragment2) == HITLS_SUCCESS); ASSERT_EQ(maxSendFragment2, 1000); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_GET_MAX_SEND_FRAGMENT_API_TC001 * @title Test the HITLS_SetMaxSendFragment and HITLS_GetMaxSendFragment. * @precon nan * @brief HITLS_SetMaxSendFragment * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set maxSendFragment to an invalid value. Expected result 2. * 3. Transfer a non-empty TLS connection handle information and set maxSendFragment to a valid value. Expected result 3 * HITLS_GetMaxSendFragment * 1. Input an empty TLS connection handle or NULL maxSendFragment pointer. Expected result 1. * 2. Transfer a non-empty TLS connection handle and maxSendFragment pointer.Expected result 3. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_CONFIG_INVALID_LENGTH is returned * 3. Returns HITLS_SUCCES. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_MAX_SEND_FRAGMENT_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; config = HITLS_CFG_NewDTLS12Config(); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); /* value > 16384 */ uint16_t maxSendFragment = 16385; ASSERT_TRUE(HITLS_SetMaxSendFragment(NULL, maxSendFragment) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetMaxSendFragment(ctx, maxSendFragment) == HITLS_CONFIG_INVALID_LENGTH); /* value < 512 */ maxSendFragment = 511; ASSERT_TRUE(HITLS_SetMaxSendFragment(ctx, maxSendFragment) == HITLS_CONFIG_INVALID_LENGTH); /* 16384 > value > 512 */ maxSendFragment = 1000; ASSERT_TRUE(HITLS_SetMaxSendFragment(ctx, maxSendFragment) == HITLS_SUCCESS); uint16_t maxSendFragment2 = 0; ASSERT_TRUE(HITLS_GetMaxSendFragment(NULL, &maxSendFragment2) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetMaxSendFragment(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetMaxSendFragment(ctx, &maxSendFragment2) == HITLS_SUCCESS); ASSERT_EQ(maxSendFragment2, 1000); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_MAX_SEND_FRAGMENT_TC001 * @title Test the HITLS_SetMaxSendFragment * @precon nan * @brief HITLS_SetMaxSendFragment * 1. Create connection. Expected result 1. * 2. set maxSendFragment to 1000 bytes. Expected result 1. * 3. Invoke hitls_write to write 1200 bytes. Expected result 2. * @expect 1. Returns HITLS_SUCCES * 2. Only 1000 bytes of data is sent @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_MAX_SEND_FRAGMENT_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; // Apply for and initialize the configuration file config = HITLS_CFG_NewDTLS12Config(); client = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(server != NULL); /* value > 512 */ uint16_t maxSendFragment = 1000; ASSERT_TRUE(HITLS_SetMaxSendFragment(client->ssl, maxSendFragment) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); const uint8_t sndBuf[1200] = {0}; uint32_t writeLen = 0; ASSERT_EQ(HITLS_Write(client->ssl, sndBuf, sizeof(sndBuf), &writeLen), HITLS_SUCCESS); ASSERT_EQ(writeLen, 1000); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_max_send_fragment.c
C
unknown
7,831
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <sys/types.h> #include <regex.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/select.h> #include <sys/time.h> #include <linux/ioctl.h> #include "securec.h" #include "bsl_sal.h" #include "sal_net.h" #include "frame_tls.h" #include "cert_callback.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "frame_io.h" #include "uio_abstraction.h" #include "tls.h" #include "tls_config.h" #include "logger.h" #include "process.h" #include "hs_ctx.h" #include "hlt.h" #include "stub_replace.h" #include "hitls_type.h" #include "frame_link.h" #include "session_type.h" #include "common_func.h" #include "hitls_func.h" #include "hitls_cert_type.h" #include "cert_mgr_ctx.h" #include "parser_frame_msg.h" #include "recv_process.h" #include "simulate_io.h" #include "rec_wrapper.h" #include "cipher_suite.h" #include "alert.h" #include "conn_init.h" #include "pack.h" #include "send_process.h" #include "cert.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "hs.h" #include "hs_state_recv.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "frame_msg.h" #include "pack_frame_msg.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "sctp_channel.h" #include "hitls_crypt_init.h" #include "hitls_session.h" #include "bsl_log.h" #include "bsl_err.h" #include "hitls_crypt_reg.h" #include "crypt_errno.h" #include "bsl_list.h" #include "hitls_cert.h" #include "parse_extensions_client.c" #include "parse_extensions_server.c" #include "parse_server_hello.c" #include "parse_client_hello.c" #include "uio_udp.c" /* END_HEADER */ /* @ * @test UT_TLS_CFG_SET_DTLS_LINK_MTU_API_TC001 * @title Test HITLS_SetLinkMtu interface * @brief 1. Create the TLS configuration object config.Expect result 1. * 2. Use config to create the client and server.Expect result 2. * 3. Invoke HITLS_SetLinkMtu, Expect result 3. * @expect 1. The config object is successfully created. * 2. The client and server are successfully created. * 3. mtu >= 256, Return HITLS_SUCCESS. mtu < 256, Return HITLS_CONFIG_INVALID_LENGTH. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_DTLS_LINK_MTU_API_TC001(void) { FRAME_Init(); uint32_t mtu = 1500; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(HITLS_SetLinkMtu(client->ssl, mtu) == HITLS_SUCCESS); server = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_SetLinkMtu(server->ssl, mtu) == HITLS_SUCCESS); /* value < 256 */ mtu = 200; ASSERT_TRUE(HITLS_SetLinkMtu(server->ssl, mtu) == HITLS_CONFIG_INVALID_LENGTH); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_NO_QUERY_MTU_API_TC001 * @title Test the HITLS_SetNoQueryMtu interfaces. * @precon nan * @brief HITLS_SetNoQueryMtu * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set noQueryMtu to an invalid value. Expected result 2. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_NO_QUERY_MTU_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; // Apply for and initialize the configuration file config = HITLS_CFG_NewDTLS12Config(); client = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(server != NULL); bool noQueryMtu = false; ASSERT_TRUE(HITLS_SetNoQueryMtu(NULL, noQueryMtu) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetNoQueryMtu(client->ssl, noQueryMtu) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetNoQueryMtu(server->ssl, noQueryMtu) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_GET_NEED_QUERY_MTU_API_TC001 * @title Test the HITLS_GetNeedQueryMtu interfaces. * @precon nan * @brief HITLS_GetNeedQueryMtu * 1. Input an empty TLS connection handle or NULL needQueryMtu pointer. Expected result 1. * 2. Input non empty ssl ctx and non empty needQueryMtu pointer. Expected result 2. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_NEED_QUERY_MTU_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; // Apply for and initialize the configuration file config = HITLS_CFG_NewDTLS12Config(); client = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(server != NULL); bool needQueryMtu = true; ASSERT_TRUE(HITLS_GetNeedQueryMtu(NULL, &needQueryMtu) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetNeedQueryMtu(NULL, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetNeedQueryMtu(client->ssl, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetNeedQueryMtu(client->ssl, &needQueryMtu) == HITLS_SUCCESS); ASSERT_EQ(needQueryMtu, false); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ int32_t STUB_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 = HITLS_REC_NORMAL_IO_BUSY; #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; } int32_t STUB_UdpSocketCtrl(BSL_UIO *uio, int32_t cmd, int32_t larg, void *parg) { (void)uio; (void)cmd; (void)larg; *(bool *)parg = true; return BSL_SUCCESS; } /** @ * @test UT_TLS_CM_MTU_EMSGSIZE_TC001 * @title Test the HITLS_SetMaxSendFragment * @precon nan * @brief HITLS_SetMaxSendFragment * 1. Create connection. Expected result 1. * 2. set maxSendFragment to 1000 bytes. Expected result 1. * 3. Invoke hitls_write to write 1200 bytes. Expected result 2. * @expect 1. Returns HITLS_SUCCES * 2. Only 1000 bytes of data is sent @ */ /* BEGIN_CASE */ void UT_TLS_CM_MTU_EMSGSIZE_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; // Apply for and initialize the configuration file config = HITLS_CFG_NewDTLS12Config(); client = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); STUB_Init(); FuncStubInfo tmpStubInfo = {0}; FuncStubInfo tmpStubInfo2 = {0}; STUB_Replace(&tmpStubInfo, REC_Write, STUB_REC_Write); STUB_Replace(&tmpStubInfo2, FRAME_Ctrl, STUB_UdpSocketCtrl); ASSERT_TRUE(HITLS_SetMtu(client->ssl, 500) == HITLS_SUCCESS); ASSERT_EQ(client->ssl->config.pmtu, 500); const uint8_t sndBuf[1200] = {0}; uint32_t writeLen = 0; ASSERT_EQ(HITLS_Write(client->ssl, sndBuf, sizeof(sndBuf), &writeLen), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(writeLen, 0); STUB_Reset(&tmpStubInfo); STUB_Reset(&tmpStubInfo2); bool needQueryMtu = false; ASSERT_TRUE(HITLS_GetNeedQueryMtu(client->ssl, &needQueryMtu) == HITLS_SUCCESS); ASSERT_EQ(needQueryMtu, true); ASSERT_EQ(HITLS_Write(client->ssl, sndBuf, sizeof(sndBuf), &writeLen), HITLS_SUCCESS); /* use min mtu 256, and the encrypt cost is need to be reduced */ ASSERT_TRUE(writeLen < 256); ASSERT_TRUE(writeLen > 0); EXIT: STUB_Reset(&tmpStubInfo); STUB_Reset(&tmpStubInfo2); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_mtu.c
C
unknown
10,035
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "frame_tls.h" #include "frame_link.h" #include "session.h" #include "hitls_config.h" #include "hitls_crypt_init.h" #include "crypt_provider_local.h" #include "crypt_eal_implprovider.h" #include "crypt_provider.h" #include "crypt_errno.h" #include "cert_callback.h" #include "test.h" #include "crypt_eal_rand.h" /* END_HEADER */ /* BEGIN_CASE */ void UT_TLS13_LOADPROVIDER_GROUP_TC001(char *path, char *get_cap_test1, int cmd) { #ifndef HITLS_TLS_FEATURE_PROVIDER (void)path; (void)get_cap_test1; (void)cmd; SKIP_TEST(); #else FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_ProvMgrCtx *providerMgr = NULL; HITLS_Config *config = NULL; int32_t ret = CRYPT_SUCCESS; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, cmd, get_cap_test1, NULL, &providerMgr); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(providerMgr != NULL); // Random Unloading Test Case ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(libCtx, GetAvailableRandAlgId(), "provider=provider_get_cap_test1", NULL, 0, NULL), CRYPT_SUCCESS); config = HITLS_CFG_ProviderNewTLS13Config(libCtx, NULL); ASSERT_TRUE(config != NULL); uint16_t group = 477; HITLS_CFG_SetGroups(config, &group, 1); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); if (libCtx != NULL) { CRYPT_EAL_LibCtxFree(libCtx); } #endif } /* END_CASE */ /* BEGIN_CASE */ void UT_TLS13_LOADPROVIDER_SIGNSCHEME_TC001(char *path, char *get_cap_test1, int cmd) { #ifndef HITLS_TLS_FEATURE_PROVIDER (void)path; (void)get_cap_test1; (void)cmd; SKIP_TEST(); #else FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_ProvMgrCtx *providerMgr = NULL; HITLS_Config *config = NULL; int32_t ret = CRYPT_SUCCESS; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, cmd, get_cap_test1, NULL, &providerMgr); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(providerMgr != NULL); // Random Unloading Test Case ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(libCtx, GetAvailableRandAlgId(), "provider=provider_get_cap_test1", NULL, 0, NULL), CRYPT_SUCCESS); config = HITLS_CFG_ProviderNewTLS13Config(libCtx, NULL); ASSERT_TRUE(config != NULL); uint16_t signScheme = 23333; HITLS_CFG_SetSignature(config, &signScheme, 1); FRAME_CertInfo certInfo = { "new_signAlg/ca.der", "new_signAlg/inter.der", "new_signAlg/client.der", NULL, "new_signAlg/client.key.der", NULL }; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); if (libCtx != NULL) { CRYPT_EAL_LibCtxFree(libCtx); } #endif } /* END_CASE */ /* BEGIN_CASE */ void UT_TLS13_LOADPROVIDER_NEWKEYTYPE_TC001(char *path, char *provider_new_alg_test, int cmd) { #ifndef HITLS_TLS_FEATURE_PROVIDER (void)path; (void)provider_new_alg_test; (void)cmd; SKIP_TEST(); #else FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; CRYPT_EAL_LibCtx *libCtx = NULL; CRYPT_EAL_ProvMgrCtx *providerMgr = NULL; HITLS_Config *config = NULL; int32_t ret = CRYPT_SUCCESS; libCtx = CRYPT_EAL_LibCtxNew(); ASSERT_TRUE(libCtx != NULL); ASSERT_EQ(CRYPT_EAL_ProviderSetLoadPath(libCtx, path), CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, cmd, provider_new_alg_test, NULL, &providerMgr); ASSERT_EQ(ret, CRYPT_SUCCESS); ret = CRYPT_EAL_ProviderLoad(libCtx, BSL_SAL_LIB_FMT_OFF, "default", NULL, NULL); ASSERT_EQ(ret, CRYPT_SUCCESS); ASSERT_TRUE(providerMgr != NULL); // Random Unloading Test Case ASSERT_EQ(CRYPT_EAL_ProviderRandInitCtx(libCtx, GetAvailableRandAlgId(), "provider=default", NULL, 0, NULL), CRYPT_SUCCESS); config = HITLS_CFG_ProviderNewTLS13Config(libCtx, NULL); ASSERT_TRUE(config != NULL); uint16_t signScheme = 24444; HITLS_CFG_SetSignature(config, &signScheme, 1); FRAME_CertInfo certInfo = { "new_keyAlg/ca.der", "new_keyAlg/inter.der", "new_keyAlg/client.der", NULL, "new_keyAlg/client.key.der", NULL }; client = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = FRAME_CreateLinkWithCert(config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); if (libCtx != NULL) { CRYPT_EAL_LibCtxFree(libCtx); } #endif } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_provider.c
C
unknown
6,469
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <stddef.h> #include "securec.h" #include "tls_config.h" #include "tls.h" #include "hitls_type.h" #include "bsl_sal.h" #include "hitls.h" #include "frame_tls.h" #include "hitls_error.h" #include "hitls_config.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "hs.h" #include "hs_ctx.h" #include "hs_state_recv.h" #include "transcript_hash.h" #include "conn_init.h" #include "recv_process.h" #include "stub_replace.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "frame_io.h" #include "frame_link.h" #include "common_func.h" #include "hitls_crypt_init.h" #include "alert.h" #define TEST_SERVERNAME_LENGTH 20 #define READ_BUF_SIZE 18432 /* END_HEADER */ typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; HITLS_TicketKeyCb serverKeyCb; } SniTestInfo; typedef struct { char servername[TEST_SERVERNAME_LENGTH + 1]; int32_t alert; } SNI_Arg; static SNI_Arg *sniArg = NULL; static char *g_serverName = "huawei.com"; static char *g_serverNameErr = "www.huawei.com"; static uint8_t *g_sessionId; static uint32_t g_sessionIdSize; int32_t ServernameCbErrOK(HITLS_Ctx *ctx, int *alert, void *arg) { (void)ctx; (void)alert; (void)arg; return HITLS_ACCEPT_SNI_ERR_OK; } void STUB_SendAlert(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { (void)ctx; (void)level; (void)description; return; } typedef struct TEST_SNI_DEAL_CB { uint32_t sniState; HITLS_SniDealCb sniDealCb; } TEST_SNI_DEAL_CB; typedef struct { HITLS_Config *clientConfig; HITLS_Config *serverConfig; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; HITLS_SniDealCb sniDealCb; HITLS_Session *clientSession; uint16_t version; BSL_UIO_TransportType type; } HandshakeTestInfo; int32_t TestCreateConfig(HITLS_Config **cfg, uint16_t version) { switch (version) { case HITLS_VERSION_DTLS12: *cfg = HITLS_CFG_NewDTLS12Config(); break; case HITLS_VERSION_TLS13: *cfg = HITLS_CFG_NewTLS13Config(); break; case HITLS_VERSION_TLS12: *cfg = HITLS_CFG_NewTLS12Config(); break; default: break; } if (*cfg == NULL) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } void FreeSNIArg(SNI_Arg *sniArg) { if (sniArg != NULL) { BSL_SAL_FREE(sniArg); } } void SetCommonConfig(HITLS_Config **config) { uint16_t groups[] = {HITLS_EC_GROUP_SECP256R1}; HITLS_CFG_SetGroups(*config, groups, sizeof(groups) / sizeof(uint16_t)); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(*config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); const uint16_t cipherSuites[] = {HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(*config, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)); HITLS_CFG_SetClientVerifySupport(*config, true); HITLS_CFG_SetExtenedMasterSecretSupport(*config, true); HITLS_CFG_SetNoClientCertSupport(*config, true); HITLS_CFG_SetRenegotiationSupport(*config, true); HITLS_CFG_SetPskServerCallback(*config, (HITLS_PskServerCb)ExampleServerCb); HITLS_CFG_SetPskClientCallback(*config, (HITLS_PskClientCb)ExampleClientCb); HITLS_CFG_SetSessionTicketSupport(*config, false); HITLS_CFG_SetCheckKeyUsage(*config, false); } static int32_t CreateLink(HandshakeTestInfo *testInfo) { testInfo->client = FRAME_CreateLink(testInfo->clientConfig, testInfo->type); if (testInfo->client == NULL) { return HITLS_INTERNAL_EXCEPTION; } if (testInfo->clientSession != NULL) { int32_t ret = HITLS_SetSession(testInfo->client->ssl, testInfo->clientSession); if (ret != HITLS_SUCCESS) { return ret; } } testInfo->server = FRAME_CreateLink(testInfo->serverConfig, testInfo->type); if (testInfo->server == NULL) { return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } static int32_t DefaultCfgAndLink(HandshakeTestInfo *testInfo) { FRAME_Init(); TestCreateConfig(&(testInfo->clientConfig), testInfo->version); if (testInfo->clientConfig == NULL) { return HITLS_INTERNAL_EXCEPTION; } SetCommonConfig(&(testInfo->clientConfig)); HITLS_CFG_SetServerName(testInfo->clientConfig, (uint8_t *)g_serverName, (uint32_t)strlen(g_serverName)); TestCreateConfig(&(testInfo->serverConfig), testInfo->version); if (testInfo->serverConfig == NULL) { return HITLS_INTERNAL_EXCEPTION; } SetCommonConfig(&(testInfo->serverConfig)); HITLS_CFG_SetServerNameCb(testInfo->serverConfig, testInfo->sniDealCb); sniArg = (SNI_Arg *)BSL_SAL_Calloc(1, sizeof(SNI_Arg)); snprintf_s(sniArg->servername, sizeof(sniArg->servername), strlen(g_serverName), "%s", g_serverName); if (HITLS_CFG_SetServerNameArg(testInfo->serverConfig, sniArg) != HITLS_SUCCESS) { return HITLS_INTERNAL_EXCEPTION; } return CreateLink(testInfo); } int32_t GetSessionId(HandshakeTestInfo *testInfo) { FRAME_Type frameType = {0}; FRAME_Msg recvframeMsg = {0}; FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo->client->io); uint8_t *recMsg = ioUserData->recMsg.msg; uint32_t recMsgLen = ioUserData->recMsg.len; frameType.handshakeType = SERVER_HELLO; frameType.recordType = REC_TYPE_HANDSHAKE; frameType.versionType = testInfo->version; uint32_t parseLen = 0; int32_t ret = FRAME_ParseMsg(&frameType, recMsg, recMsgLen, &recvframeMsg, &parseLen); if (ret != HITLS_SUCCESS) { return ret; } FRAME_ServerHelloMsg *serverHello = &recvframeMsg.body.hsMsg.body.serverHello; g_sessionIdSize = serverHello->sessionIdSize.data; BSL_SAL_FREE(g_sessionId); g_sessionId = BSL_SAL_Dump(serverHello->sessionId.data, g_sessionIdSize); FRAME_CleanMsg(&frameType, &recvframeMsg); return HITLS_SUCCESS; } int32_t FirstHandshake(HandshakeTestInfo *testInfo) { int32_t ret = FRAME_CreateConnection(testInfo->client, testInfo->server, true, TRY_RECV_SERVER_HELLO); if (ret != HITLS_SUCCESS) { return ret; } ret = GetSessionId(testInfo); if (ret != HITLS_SUCCESS) { return ret; } ret = FRAME_CreateConnection(testInfo->client, testInfo->server, true, HS_STATE_BUTT); if (ret != HITLS_SUCCESS) { return ret; } uint8_t data[] = "Hello World"; uint32_t writeLen; ret = HITLS_Write(testInfo->server->ssl, data, sizeof(data), &writeLen); if (ret != HITLS_SUCCESS) { return ret; } uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ret = FRAME_TrasferMsgBetweenLink(testInfo->server, testInfo->client); if (ret != HITLS_SUCCESS) { return ret; } ret = HITLS_Read(testInfo->client->ssl, readBuf, READ_BUF_SIZE, &readLen); if (ret != HITLS_SUCCESS) { return ret; } testInfo->clientSession = HITLS_GetDupSession(testInfo->client->ssl); FRAME_FreeLink(testInfo->client); testInfo->client = NULL; FRAME_FreeLink(testInfo->server); testInfo->server = NULL; return HITLS_SUCCESS; } /* @ * @test UT_TLS_SNI_RESUME_SERVERNAME_FUNC_TC001 * @title During session resumption, the serverName extension of clientHello is different from that in first handshake * @precon nan * @brief 1. For the first handshake, set serverName to huawei.com in the clientHello. Expected result 1 2. During session resumption, changed serverName of clientHello to www.sss.com. Expected result 2 3. process the client hello. Expected result 2 * @expect 1. The serverName extension is set successfully and the handshake succeeds 2. return success @ */ /* BEGIN_CASE */ void UT_TLS_SNI_RESUME_SERVERNAME_FUNC_TC001(int version, int type) { g_sessionId = NULL; g_sessionIdSize = 0; HandshakeTestInfo testInfo = {0}; testInfo.version = (uint16_t)version; testInfo.type = (BSL_UIO_TransportType)type; testInfo.sniDealCb = ServernameCbErrOK; ASSERT_EQ(DefaultCfgAndLink(&testInfo), HITLS_SUCCESS); ASSERT_EQ(FirstHandshake(&testInfo), HITLS_SUCCESS); ASSERT_TRUE(testInfo.clientSession != NULL); ASSERT_TRUE(CreateLink(&testInfo) == HITLS_SUCCESS); ASSERT_TRUE( FRAME_CreateConnection(testInfo.client, testInfo.server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(testInfo.server->ssl->hsCtx->state == TRY_RECV_CLIENT_HELLO); CONN_Deinit(testInfo.server->ssl); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(testInfo.server->io); uint8_t *buffer = ioUserData->recMsg.msg; uint32_t len = ioUserData->recMsg.len; ASSERT_TRUE(len != 0); FRAME_Msg frameMsg = {0}; uint32_t parseLen = 0; HS_Init(testInfo.server->ssl); ASSERT_TRUE(ParserTotalRecord(testInfo.server, &frameMsg, buffer, len, &parseLen) == HITLS_SUCCESS); ASSERT_TRUE(frameMsg.body.handshakeMsg.type == CLIENT_HELLO); char *hostName = "www.sss.com"; uint8_t *serverName = frameMsg.body.handshakeMsg.body.clientHello.extension.content.serverName; uint16_t serverNameSize = frameMsg.body.handshakeMsg.body.clientHello.extension.content.serverNameSize; frameMsg.body.handshakeMsg.body.clientHello.extension.content.serverNameSize = strlen(hostName) + 1; frameMsg.body.handshakeMsg.body.clientHello.extension.content.serverName = (uint8_t *)hostName; testInfo.server->ssl->method.sendAlert = STUB_SendAlert; CONN_Init(testInfo.server->ssl); if (testInfo.type == BSL_UIO_TCP) { ASSERT_TRUE(Tls12ServerRecvClientHelloProcess(testInfo.server->ssl, &frameMsg.body.handshakeMsg, true) == HITLS_SUCCESS); } else { ASSERT_TRUE(DtlsServerRecvClientHelloProcess(testInfo.server->ssl, &frameMsg.body.handshakeMsg) == HITLS_SUCCESS); } frameMsg.body.handshakeMsg.body.clientHello.extension.content.serverName = serverName; frameMsg.body.handshakeMsg.body.clientHello.extension.content.serverNameSize = serverNameSize; EXIT: BSL_SAL_FREE(g_sessionId); CleanRecordBody(&frameMsg); HITLS_CFG_FreeConfig(testInfo.clientConfig); HITLS_CFG_FreeConfig(testInfo.serverConfig); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); HITLS_SESS_Free(testInfo.clientSession); FreeSNIArg(sniArg); } /* END_CASE */ void *ExampleServerNameArg1(void) { return sniArg; } int32_t ExampleServerNameCb1(HITLS_Ctx *ctx, int *alert, void *arg) { (void)arg; (void)alert; const char *server_servername = "huawei.com"; const char *client_servername = HITLS_GetServerName(ctx, HITLS_SNI_HOSTNAME_TYPE); if (client_servername != NULL && server_servername != NULL) { if (strcmp(client_servername, server_servername) == 0){ printf("\nHiTLS ServerNameCb return HITLS_ACCEPT_SNI_ERR_OK\n"); return HITLS_ACCEPT_SNI_ERR_OK; } else { printf("\nHiTLS ServerNameCb return HITLS_ACCEPT_SNI_ERR_ALERT_FATAL\n"); return HITLS_ACCEPT_SNI_ERR_ALERT_FATAL; } } else{ if (client_servername == NULL) { printf("\nHiTLS Server get client_servername is NULL!\n"); } else if (server_servername == NULL){ printf("\nHiTLS Server get server_servername is NULL!\n"); } } printf("\nHiTLS ServerNameCb return HITLS_ACCEPT_SNI_ERR_NOACK\n"); return HITLS_ACCEPT_SNI_ERR_NOACK; } /* @ * @test UT_TLS_SNI_RESUME_SERVERNAME_FUNC_TC002 * @title The TLS13 session is resumed. The client hello message carries the SNI, and the SNI value is different from that of the first connection setup. * @precon nan * @brief 1. For the first handshake, set serverName to huawei.com in the clientHello. Expected result 1 2. During session resumption, changed serverName of clientHello to www.huawei.com. Expected result 2 3. process the client hello. Expected result 2 * @expect 1. The serverName extension is set successfully and the handshake succeeds 2. return success @ */ /* BEGIN_CASE */ void UT_TLS_SNI_RESUME_SERVERNAME_FUNC_TC002() { FRAME_Init(); HITLS_Config *clientconfig = HITLS_CFG_NewTLS13Config(); HITLS_Config *serverconfig = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(serverconfig != NULL); ASSERT_TRUE(clientconfig != NULL); HITLS_CFG_SetServerNameCb(serverconfig, ExampleServerNameCb1); HITLS_CFG_SetServerNameArg(serverconfig, ExampleServerNameArg1); HITLS_CFG_SetServerName(clientconfig, (uint8_t *)g_serverName, strlen(g_serverName)); FRAME_LinkObj *client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *Session = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(Session != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(clientconfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(serverconfig, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, Session), HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetServerName(client->ssl, (uint8_t *)g_serverNameErr, strlen(g_serverNameErr)) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_MSG_HANDLE_SNI_UNRECOGNIZED_NAME); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(server->ssl, &alertInfo); ASSERT_EQ(alertInfo.flag, ALERT_FLAG_SEND); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, ALERT_UNRECOGNIZED_NAME); EXIT: HITLS_CFG_FreeConfig(clientconfig); HITLS_CFG_FreeConfig(serverconfig); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(Session); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_servername_function.c
C
unknown
15,487
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <stdint.h> #include "config.h" #include "hitls.h" #include "hitls_func.h" #include "hitls_error.h" /* END_HEADER */ static char *g_serverName = "www.example.com"; int32_t ServernameCbErrOK(HITLS_Ctx *ctx, int *alert, void *arg) { (void)ctx; (void)alert; (void)arg; return HITLS_ACCEPT_SNI_ERR_OK; } #define HITLS_CFG_MAX_SIZE 1024 /** @ * @test UT_TLS_CFG_UPREF_FUNC_TC001 * @title test HITLS_CFG_SetServerName/HITLS_CFG_SetServerNameCb/HITLS_CFG_SetServerNameArg/HITLS_GetServernameType * interface * * @brief 1. Apply for and initialize config.Expect result 1 2. Invoke the HITLS_CFG_NewTLS12Config interface and transfer the config parameter.Expect result 2. 3. Set serverNameStrlen HITLS_CFG_MAX_SIZE + 1;Invoke the HITLS_CFG_SetServerName interface Expect result 3. 4. Invoke the HITLS_CFG_NewTLS12Config interface.Expect result 4. 5. input parameters is NULL,Invoke the HITLS_CFG_NewTLS12Config interface and .Expect result 2. 6. Invoke the HITLS_CFG_SetServerNameCb interface ,Expect result 2. 7. Invoke the HITLS_CFG_SetServerNameArg interface ,Expect result 2. 8. Invoke the HITLS_CFG_GetServerNameCb interface ,Expect result 2. 9. Invoke the HITLS_CFG_GetServerNameArg interface ,Expect result 2. 10. Invoke the HITLS_SetServerName interface ,Expect result 2. 11. Invoke the HITLS_SetServerName interface ,Expect result 2. 12. Invoke the HITLS_SetServerName interface ,Expect result 6. 13. Invoke the HITLS_SetServerName interface ,Expect result 6. 14. Invoke the HITLS_GetServernameType interface ,Expect result 1. * @expect 1. return Not NULL 2. return HITLS_NULL_INPUT 3. return HITLS_CONFIG_INVALID_LENGTH 4. return SUCCESS 5. return HITLS_NULL_INPUT 6. return NULL @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_SERVERNAME_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); ASSERT_TRUE(HITLS_CFG_SetServerName(NULL, (uint8_t *)g_serverName, (uint32_t)strlen(g_serverName)) == HITLS_NULL_INPUT); uint32_t errLen = HITLS_CFG_MAX_SIZE + 1; ASSERT_TRUE(HITLS_CFG_SetServerName(config, (uint8_t *)g_serverName, errLen) == HITLS_CONFIG_INVALID_LENGTH); ASSERT_TRUE(HITLS_CFG_SetServerName(config, (uint8_t *)g_serverName, (uint32_t)strlen(g_serverName)) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetServerName(NULL, NULL, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetServerNameCb(NULL, ServernameCbErrOK) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetServerNameArg(NULL, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetServerNameCb(NULL, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetServerNameArg(NULL, NULL) == HITLS_NULL_INPUT); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetServerName(ctx, NULL, 0) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetServerName(NULL, (uint8_t *)g_serverName, 0) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetServerName(ctx, HITLS_SNI_BUTT) == NULL); ASSERT_TRUE(HITLS_GetServerName(NULL, HITLS_SNI_HOSTNAME_TYPE) == NULL); ASSERT_TRUE(HITLS_GetServernameType(ctx) != 0); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_servername_interface.c
C
unknown
4,055
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "frame_tls.h" #include "frame_link.h" #include "session.h" #include "hitls_config.h" #include "hitls_crypt_init.h" /* END_HEADER */ static int32_t ServernameCbErrOK(HITLS_Ctx *ctx, int *alert, void *arg) { (void)ctx; (void)alert; (void)arg; return HITLS_ACCEPT_SNI_ERR_OK; } /** @ * @test UT_TLS12_RESUME_FUNC_TC001 * @title Test the session resume of tls12. * * @brief 1. at first handshake, config serverName, and sessionidCtx. Expect result 1 2. at second handshake, Expect result 2 * @expect 1. connect success 2. resume success @ */ /* BEGIN_CASE */ void UT_TLS12_RESUME_FUNC_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); HITLS_CFG_SetServerName(config, (uint8_t *)"www.test.com", (uint32_t)strlen((char *)"www.test.com")); HITLS_CFG_SetServerNameCb(config, ServernameCbErrOK); char *sessionIdCtx1 = "123456789"; ASSERT_EQ(HITLS_CFG_SetSessionIdCtx(config, (const uint8_t *)sessionIdCtx1, strlen(sessionIdCtx1)), HITLS_SUCCESS); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); HITLS_Session *clientSession = HITLS_GetDupSession(client->ssl); ASSERT_TRUE(clientSession != NULL); FRAME_FreeLink(client); client = NULL; FRAME_FreeLink(server); server = NULL; client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetSession(client->ssl, clientSession), HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_EQ(HITLS_IsSessionReused(client->ssl, &isReused), HITLS_SUCCESS); ASSERT_EQ(isReused, 1); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); HITLS_SESS_Free(clientSession); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_session_ticket.c
C
unknown
2,736
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "securec.h" #include "hlt.h" #include "hitls_error.h" #include "hitls_func.h" #include "conn_init.h" #include "frame_tls.h" #include "frame_link.h" #include "alert.h" #include "stub_replace.h" #include "hs_common.h" #include "change_cipher_spec.h" #include "hs.h" #include "simulate_io.h" #include "rec_header.h" #include "rec_wrapper.h" #include "record.h" #include "app.c" /* END_HEADER */ #define READ_BUF_SIZE 18432 #define MAX_DIGEST_SIZE 64UL /* The longest known is SHA512 */ uint32_t g_uiPort = 8890; static uint32_t g_time = 0; int32_t STUB_APP_Read(TLS_Ctx *ctx, uint8_t *buf, uint32_t num, uint32_t *readLen) { int32_t ret; uint32_t readbytes; g_time++; if(g_time == 2) { return HITLS_REC_ERR_IO_EXCEPTION; } if (ctx == NULL || buf == NULL || num == 0) { return HITLS_APP_ERR_ZERO_READ_BUF_LEN; } // read data to the buffer in non-blocking mode do { ret = ReadAppData(ctx, buf, num, &readbytes); if (ret != HITLS_SUCCESS) { return ret; } } while (readbytes == 0); // do not exit the loop until data is read *readLen = readbytes; return HITLS_SUCCESS; } /** @ * @test UT_TLS_CM_SSL_MODE_AUTO_RETRY_TC001 * @title UT_TLS_CM_SSL_MODE_AUTO_RETRY_TC001 * @brief * 1. Create connection. Expected result 1 is obtained. * 2. Unset the auto retry mode, get keyupdate message. Expected result 2 is obtained. * @expect * 1. Successfully created connection. * 2. After receive keyupdate message, the link will not try to read another app message @ */ /* BEGIN_CASE */ void UT_TLS_CM_SSL_MODE_AUTO_RETRY_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint32_t len = 0; ASSERT_TRUE(HITLS_Write(client->ssl, (uint8_t *)"Hello World", strlen("Hello World"), &len) == HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); ret = HITLS_KeyUpdate(client->ssl, HITLS_UPDATE_NOT_REQUESTED); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_TRUE(HITLS_ClearModeSupport(server->ssl, HITLS_MODE_AUTO_RETRY) == HITLS_SUCCESS); g_time = 0; FuncStubInfo tmpRpInfo = {0}; STUB_Replace(&tmpRpInfo, APP_Read, STUB_APP_Read); ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&tmpRpInfo); g_time = 0; } /* END_CASE */ /** @ * @test UT_TLS_CM_SSL_MODE_AUTO_RETRY_TC002 * @title UT_TLS_CM_SSL_MODE_AUTO_RETRY_TC002 * @brief * 1. Create connection. Expected result 1 is obtained. * 2. Unset the auto retry mode, Send Hello request. Expected result 2 is obtained. * @expect * 1. Successfully created connection. * 2. After receive Hello request and send no_renegotiation alert, the link will not try to read another app message @ */ /* BEGIN_CASE */ void UT_TLS_CM_SSL_MODE_AUTO_RETRY_TC002() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint32_t len = 0; ASSERT_TRUE(HITLS_Write(client->ssl, (uint8_t *)"Hello World", strlen("Hello World"), &len) == HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); ASSERT_EQ(HITLS_SetRenegotiationSupport(client->ssl, false), HITLS_SUCCESS); ASSERT_EQ(HITLS_Renegotiate(server->ssl), HITLS_SUCCESS); ASSERT_TRUE(HITLS_Accept(server->ssl) == HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(server, client), HITLS_SUCCESS); ASSERT_TRUE(HITLS_ClearModeSupport(client->ssl, HITLS_MODE_AUTO_RETRY) == HITLS_SUCCESS); g_time = 0; FuncStubInfo tmpRpInfo = {0}; STUB_Replace(&tmpRpInfo, APP_Read, STUB_APP_Read); ASSERT_EQ(HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&tmpRpInfo); g_time = 0; } /* END_CASE */ /** @ * @test UT_TLS_CM_SSL_MODE_MOVE_BUFFER_TC001 * @title UT_TLS_CM_SSL_MODE_MOVE_BUFFER_TC001 * @brief * 1. Create connection. Expected result 1 is obtained. * 2. Set moving buffer mode, when io busy, using different buffer retry. Expected result 2 is obtained. * @expect * 1. Successfully created connection. * 2. Retry success. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SSL_MODE_MOVE_BUFFER_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetModeSupport(client->ssl, HITLS_MODE_ACCEPT_MOVING_WRITE_BUFFER) == HITLS_SUCCESS); uint8_t data[] = "hello world"; uint8_t data2[] = "hello world"; uint32_t len = 0; ASSERT_TRUE(HITLS_Write(client->ssl, data, sizeof(data), &len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Write(client->ssl, data, sizeof(data), &len) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Write(client->ssl, data2, sizeof(data2), &len), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_SSL_MODE_MOVE_BUFFER_TC002 * @title UT_TLS_CM_SSL_MODE_MOVE_BUFFER_TC002 * @brief * 1. Create connection. Expected result 1 is obtained. * 2. Set moving buffer mode, when io busy, using shorter buffer retry. Expected result 2 is obtained. * @expect * 1. Successfully created connection. * 2. Send alert. Before send alert, flush the out buffer first. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SSL_MODE_MOVE_BUFFER_TC002() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetModeSupport(client->ssl, HITLS_MODE_ACCEPT_MOVING_WRITE_BUFFER) == HITLS_SUCCESS); uint8_t data[] = "hello world"; uint32_t len = 0; ASSERT_TRUE(HITLS_Write(client->ssl, data, sizeof(data), &len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Write(client->ssl, data, sizeof(data), &len) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_TRUE(readLen == sizeof(data)); ASSERT_TRUE(memcmp("hello world", readBuf, readLen) == 0); ASSERT_EQ(HITLS_Write(client->ssl, data, 1, &len), HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(client->ssl->state, CM_STATE_ALERTING); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_EQ(server->ssl->state, CM_STATE_TRANSPORTING); ASSERT_EQ(HITLS_Write(client->ssl, data, 1, &len), HITLS_CM_LINK_FATAL_ALERTED); ASSERT_EQ(client->ssl->state, CM_STATE_ALERTED); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_EQ(server->ssl->state, CM_STATE_ALERTED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_SSL_MODE_RELEASE_BUFFER_TC001 * @title UT_TLS_CM_SSL_MODE_RELEASE_BUFFER_TC001 * @brief * 1. Set release buffer mode. Create connection. Expected result 1 is obtained. * @expect * 1. Successfully created connection. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SSL_MODE_RELEASE_BUFFER_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_SetModeSupport(client->ssl, HITLS_MODE_RELEASE_BUFFERS) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetModeSupport(server->ssl, HITLS_MODE_RELEASE_BUFFERS) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint32_t len = 0; ASSERT_TRUE(HITLS_Write(client->ssl, (uint8_t *)"Hello World", strlen("Hello World"), &len) == HITLS_SUCCESS); ASSERT_EQ(FRAME_TrasferMsgBetweenLink(client, server), HITLS_SUCCESS); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen), HITLS_SUCCESS); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_ssl_mode.c
C
unknown
13,843
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "hlt.h" #include "logger.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "crypt_util_rand.h" #include "helper.h" #include "hitls.h" #include "alert.h" #include "hitls_type.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "rec_wrapper.h" #include "common_func.h" #include "stub_crypt.h" /* END_HEADER */ /* @ * @test SDV_TLS_CFG_SET_TLS_FALLBACK_SCSV_TC001 * @title Test the behavior of the server when it receives the TLS_FALLBACK_SCSV algorithm suite carried by the lower version of clienthello. * @brief 1. the client creates the config of tls12, and the server creates the config of tls13.Expect result 1. * 2. the client sets HITLS_MODE_SEND_FALLBACK_SCSV.expect result 2. * 3. connection establishment, Expect result 3. * @expect 1. The config object is successfully created. * 2. return HITLS_SUCCES. * 3. Failed to establish connection, send alert ALERT_INAPPROPRIATE_FALLBACK. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_SET_TLS_FALLBACK_SCSV_TC001(int isSetMode) { #ifdef HITLS_TLS_FEATURE_MODE HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, 18256, false); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS_ALL, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); if (isSetMode) { HLT_SetModeSupport(clientCtxConfig, HITLS_MODE_SEND_FALLBACK_SCSV); } clientRes = HLT_ProcessTlsInit(localProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); HLT_TlsConnect(clientRes->ssl); // Wait the remote. int ret = HLT_GetTlsAcceptResult(serverRes); if (isSetMode) { ASSERT_EQ(ret, HITLS_MSG_HANDLE_ERR_INAPPROPRIATE_FALLBACK); ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(clientRes->ssl, &alertInfo); ASSERT_EQ(alertInfo.flag, ALERT_FLAG_RECV); ASSERT_EQ(alertInfo.level, ALERT_LEVEL_FATAL); ASSERT_EQ(alertInfo.description, ALERT_INAPPROPRIATE_FALLBACK); } else { ASSERT_EQ(ret, HITLS_SUCCESS); } EXIT: HLT_FreeAllProcess(); #endif } /* END_CASE */ /* @ * @test UT_TLS_CFG_SET_TLS_FALLBACK_SCSV_TC001 * @title Test the behavior of the server when it receives the TLS_FALLBACK_SCSV algorithm suite carried by the * lower version of clienthello. * @brief 1. the client creates the config of tls12, and the server creates the config of tls13.Expect result 1. * 2. the client sets HITLS_MODE_SEND_FALLBACK_SCSV.expect result 2. * 3. connection establishment, Expect result 3. * @expect 1. The config object is successfully created. * 2. return HITLS_SUCCES. * 3. Failed to establish connection, send alert ALERT_INAPPROPRIATE_FALLBACK. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_TLS_FALLBACK_SCSV_TC001(int isSetMode) { #ifdef HITLS_TLS_FEATURE_MODE FRAME_Init(); HITLS_Config *c_config = NULL; HITLS_Config *s_config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; c_config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(c_config != NULL); if (isSetMode) { HITLS_CFG_SetModeSupport(c_config, HITLS_MODE_SEND_FALLBACK_SCSV); } s_config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(s_config != NULL); client = FRAME_CreateLink(c_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); if (isSetMode) { ASSERT_EQ(ret, HITLS_MSG_HANDLE_ERR_INAPPROPRIATE_FALLBACK); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_INAPPROPRIATE_FALLBACK); } else { ASSERT_EQ(ret, HITLS_SUCCESS); } EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); #endif } /* END_CASE */ /* @ * @test UT_TLS_CFG_SET_TLS_FALLBACK_SCSV_TC002 * @title Test the behavior of the server when it disables tls13 and receives the TLS_FALLBACK_SCSV algorithm suite * carried by the lower version of clienthello. * @brief 1. the client creates the config of tls12, and the server creates the config of tlsall.Expect result 1. * 2. the client sets HITLS_MODE_SEND_FALLBACK_SCSV. The server disables tls13. expect result 2. * 3. connection establishment, Expect result 3. * @expect 1. The config object is successfully created. * 2. return HITLS_SUCCES. * 3. return HITLS_SUCCES. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_TLS_FALLBACK_SCSV_TC002() { #ifdef HITLS_TLS_FEATURE_MODE FRAME_Init(); HITLS_Config *c_config = NULL; HITLS_Config *s_config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; c_config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(c_config != NULL); HITLS_CFG_SetModeSupport(c_config, HITLS_MODE_SEND_FALLBACK_SCSV); s_config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(s_config != NULL); ASSERT_TRUE(HITLS_CFG_SetVersionForbid(s_config, HITLS_VERSION_TLS13) == HITLS_SUCCESS); client = FRAME_CreateLink(c_config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(s_config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); int32_t ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_EQ(ret, HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(c_config); HITLS_CFG_FreeConfig(s_config); FRAME_FreeLink(client); FRAME_FreeLink(server); #endif } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_frame_tls_fallback_scsv_rfc7507.c
C
unknown
6,903
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "hlt.h" #include "logger.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "crypt_util_rand.h" #include "helper.h" #include "hitls.h" #include "frame_tls.h" #include "hitls_type.h" #include "rec_wrapper.h" #include "hs_ctx.h" #include "tls.h" #include "hitls_config.h" #include "alert.h" #define READ_BUF_LEN_18K (18 * 1024) /* END_HEADER */ static uint32_t g_uiPort = 16888; static uint32_t retry_count = 0; int32_t cert_callback(HITLS_Ctx *ctx, void *arg) { (void)ctx; uint32_t *num = arg; if (*num == 3) { return HITLS_CERT_CALLBACK_FAILED; } if ((*num)++ == 0) { return HITLS_CERT_CALLBACK_RETRY; } return HITLS_CERT_CALLBACK_SUCCESS; } /** * @test SDV_TLS_CERT_CALLBACK_FUNC_TC01 * @title cert Callback Function Test Case 1 * @precon nan * @brief Server sets the cert callback function, and the cert callback function return HITLS_CERT_CALLBACK_FAILED. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The server returns HITLS_CALLBACK_CERT_ERROR. */ /* BEGIN_CASE */ void SDV_TLS_CERT_CALLBACK_FUNC_TC01(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); int32_t flag = 3; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_SetCertCb(serverCtxConfig, cert_callback, &flag); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_CALLBACK_CERT_ERROR); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** * @test SDV_TLS_CERT_CALLBACK_FUNC_TC02 * @title cert Callback Function Test Case 2 * @precon nan * @brief Server sets the cert callback function, and the cert callback function return HITLS_CERT_CALLBACK_RETRY. * The cert callback function is called twice, and the second time it returns HITLS_CERT_CALLBACK_SUCCESS. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The server returns HITLS_SUCCESS. */ /* BEGIN_CASE */ void SDV_TLS_CERT_CALLBACK_FUNC_TC02(int version) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_SetCertCb(serverCtxConfig, cert_callback, &retry_count); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_SUCCESS); ASSERT_EQ(retry_count, 2); EXIT: HLT_FreeAllProcess(); retry_count = 0; } /* END_CASE */ /** * @test SDV_TLS_CERT_CALLBACK_FUNC_TC03 * @title cert Callback Function Test Case 3 * @precon nan * @brief Client sets the cert callback function, and the cert callback function return HITLS_CERT_CALLBACK_RETRY. * Server set client verify support, The cert callback function is called twice, * and the second time it returns HITLS_CERT_CALLBACK_SUCCESS. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The link establishment is successful and cert callback function is called twice. */ /* BEGIN_CASE */ void SDV_TLS_CERT_CALLBACK_FUNC_TC03(int version) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetClientVerifySupport(serverCtxConfig, true); serverRes = HLT_ProcessTlsAccept(remoteProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetClientVerifySupport(clientCtxConfig, true); HLT_SetCertCb(clientCtxConfig, cert_callback, &retry_count); clientRes = HLT_ProcessTlsConnect(localProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(retry_count, 2); EXIT: HLT_FreeAllProcess(); retry_count = 0; } /* END_CASE */ /** * @test SDV_TLS_CERT_CALLBACK_FUNC_TC04 * @title cert Callback Function Test Case 4 * @precon nan * @brief Client sets the cert callback function, and the cert callback function return HITLS_CERT_CALLBACK_RETRY. * Server set client verify support and post handshake auth, The cert callback function is called twice, * and the second time it returns HITLS_CERT_CALLBACK_SUCCESS. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The link establishment is successful and cert callback function is called twice. */ /* BEGIN_CASE */ void SDV_TLS_CERT_CALLBACK_FUNC_TC04(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetClientVerifySupport(serverCtxConfig, true); HLT_SetPostHandshakeAuth(serverCtxConfig, true); serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetClientVerifySupport(clientCtxConfig, true); HLT_SetPostHandshakeAuth(clientCtxConfig, true); HLT_SetCertCb(clientCtxConfig, cert_callback, &retry_count); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(retry_count, 0); ASSERT_TRUE(HLT_RpcTlsVerifyClientPostHandshake(remoteProcess, serverRes->sslId) == HITLS_SUCCESS); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsWrite(remoteProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); ASSERT_EQ(HLT_ProcessTlsRead(localProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen), 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); ASSERT_EQ(retry_count, 2); EXIT: HLT_FreeAllProcess(); retry_count = 0; } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_hlt_cert_cb.c
C
unknown
8,648
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "hlt.h" #include "logger.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "crypt_util_rand.h" #include "helper.h" #include "hitls.h" #include "frame_tls.h" #include "hitls_type.h" #include "rec_wrapper.h" #include "hs_ctx.h" #include "tls.h" #include "hitls_config.h" #include "alert.h" #define READ_BUF_LEN_18K (18 * 1024) /* END_HEADER */ static uint32_t g_uiPort = 16888; static uint32_t retry_count = 0; int32_t client_hello_test_renegotiation_callback(HITLS_Ctx *ctx, int32_t *alert, void *arg) { (void)arg; uint8_t verifyData[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataSize = 0; HITLS_GetFinishVerifyData(ctx, verifyData, sizeof(verifyData), &verifyDataSize); if (verifyDataSize != 0) { *alert = ALERT_NO_RENEGOTIATION; return HITLS_CLIENT_HELLO_FAILED; } HITLS_GetPeerFinishVerifyData(ctx, verifyData, sizeof(verifyData), &verifyDataSize); if (verifyDataSize != 0) { *alert = ALERT_NO_RENEGOTIATION; return HITLS_CLIENT_HELLO_FAILED; } return HITLS_CLIENT_HELLO_SUCCESS; } int32_t client_hello_callback(HITLS_Ctx *ctx, int32_t *alert, void *arg) { (void)ctx; uint32_t *num = arg; *alert = ALERT_INTERNAL_ERROR; if ((*num)++ == 0) { return HITLS_CLIENT_HELLO_RETRY; } return HITLS_CLIENT_HELLO_SUCCESS; } int32_t full_client_hello_callback(HITLS_Ctx *ctx, int32_t *alert, void *arg) { uint16_t *cipher; uint16_t cipherLen; uint16_t *exts; uint8_t extLen; uint8_t *random; uint8_t randomLen; uint8_t *extBuff; uint32_t extBuffLen; uint32_t *num = arg; const uint16_t expected_ciphers[] = {0xc02c, 0x00ff}; const uint16_t expected_extensions[] = {13, 10, 11, 23, 22}; *alert = ALERT_INTERNAL_ERROR; if (*num == 0) { return HITLS_CLIENT_HELLO_RETRY; } if (*num == 1) { return HITLS_CLIENT_HELLO_FAILED; } /* Make sure we can defer processing and get called back. */ ASSERT_TRUE(HITLS_ClientHelloGetRandom(ctx, &random, &randomLen) == HITLS_SUCCESS); ASSERT_TRUE(random != NULL); ASSERT_TRUE(randomLen == 32); ASSERT_TRUE(HITLS_ClientHelloGetCiphers(ctx, &cipher, &cipherLen) == HITLS_SUCCESS); ASSERT_TRUE(cipher != NULL); ASSERT_TRUE(cipherLen != 0); // Compare expected_ciphers and cipher ASSERT_TRUE(cipherLen == sizeof(expected_ciphers) / sizeof(expected_ciphers[0])); ASSERT_EQ(memcmp(cipher, expected_ciphers, cipherLen * sizeof(uint16_t)), 0); ASSERT_TRUE(HITLS_ClientHelloGetExtensionsPresent(ctx, &exts, &extLen) == HITLS_SUCCESS); ASSERT_TRUE(exts != NULL); ASSERT_TRUE(extLen != 0); // Compare expected_extensions and exts ASSERT_TRUE(extLen == sizeof(expected_extensions) / sizeof(expected_extensions[0])); for (uint16_t i = 0; i < extLen; ++i) { ASSERT_TRUE(exts[i] == expected_extensions[i]); } BSL_SAL_FREE(exts); ASSERT_TRUE(HITLS_ClientHelloGetExtension(ctx, 13, &extBuff, &extBuffLen) == HITLS_SUCCESS); ASSERT_TRUE(extBuff != NULL); ASSERT_TRUE(extBuffLen != 0); return HITLS_CLIENT_HELLO_SUCCESS; EXIT: return HITLS_CLIENT_HELLO_FAILED; } /** * @test SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC01 * @title Client Hello Callback Function Test Case 1 * @precon nan * @brief Server sets the client hello callback function, and the client hello callback function * return HITLS_CLIENT_HELLO_FAILED. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The server returns HITLS_CALLBACK_CLIENT_HELLO_ERROR. */ /* BEGIN_CASE */ void SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC01(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); int32_t flag = 1; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ; HLT_SetClientHelloCb(serverCtxConfig, full_client_hello_callback, &flag); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes == NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_CALLBACK_CLIENT_HELLO_ERROR); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** * @test SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC02 * @title Client Hello Callback Function Test Case 2 * @precon nan * @brief Server sets the client hello callback function, and the client hello callback function * return HITLS_CLIENT_HELLO_SUCCESS. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The server returns HITLS_SUCCESS. */ /* BEGIN_CASE */ void SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC02(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); int32_t flag = 2; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_SetClientHelloCb(serverCtxConfig, full_client_hello_callback, &flag); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_SUCCESS); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** * @test SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC03 * @title Client Hello Callback Function Test Case 3 * @precon nan * @brief Server sets the client hello callback function, and the client hello callback function * return HITLS_CLIENT_HELLO_RETRY. The client hello callback function is called twice, * and the second time it returns HITLS_CLIENT_HELLO_SUCCESS. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The server returns HITLS_SUCCESS. */ /* BEGIN_CASE */ void SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC03(int version) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ; HLT_SetClientHelloCb(serverCtxConfig, client_hello_callback, &retry_count); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_SUCCESS); ASSERT_EQ(retry_count, 2); EXIT: HLT_FreeAllProcess(); retry_count = 0; } /* END_CASE */ /** * @test SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC04 * @title Client Hello Callback Function Test Case 4 * @precon nan * @brief Server sets the client hello callback function, and the client hello callback function * return HITLS_CLIENT_HELLO_SUCCESS. * On renegotiation, the client hello callback returns HITLS_CLIENT_HELLO_FAILED. * The server supports renegotiation, and the client does not support renegotiation. * establish a TLS connection between the client and server, expect result 1. * server starts renegotiation, and the client hello callback function returns HITLS_CLIENT_HELLO_FAILED. * expect result 2. * @expect 1. The link establishment is successful. * 2. The server returns ALERT_NO_RENEGOTIATION. */ /* BEGIN_CASE */ void SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC04(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ; HLT_SetClientHelloCb(serverCtxConfig, client_hello_test_renegotiation_callback, &retry_count); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetRenegotiationSupport(serverCtxConfig, true); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetRenegotiationSupport(clientCtxConfig, true); HLT_SetLegacyRenegotiateSupport(clientCtxConfig, true); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); ASSERT_EQ(HITLS_Renegotiate(serverRes->ssl), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(serverRes->ssl), HITLS_SUCCESS); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(HLT_ProcessTlsRead(localProcess, serverRes, readBuf, READ_BUF_LEN_18K, &readLen), HITLS_CALLBACK_CLIENT_HELLO_ERROR); ALERT_Info info = {0}; ALERT_GetInfo(serverRes->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_NO_RENEGOTIATION); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** * @test SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC05 * @title Client Hello Callback Function Test Case 5 * @precon nan * @brief Server sets the client hello callback function, and the client hello callback function return * HITLS_CLIENT_HELLO_RETRY. * The client hello callback function is called three times, and the third time it returns * HITLS_CLIENT_HELLO_SUCCESS. * establish a TLS connection between the client and server, expect result 1. * @expect 1. The server returns HITLS_SUCCESS. * 2. The client hello callback function is called three times. * 3. The retry_count is 3. */ /* BEGIN_CASE */ void SDV_TLS_CLIENT_HELLO_CALLBACK_FUNC_TC05(void) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_SetClientHelloCb(serverCtxConfig, client_hello_callback, &retry_count); HLT_SetGroups(serverCtxConfig, "HITLS_EC_GROUP_SECP256R1"); ASSERT_TRUE(serverCtxConfig != NULL); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_CURVE25519:HITLS_EC_GROUP_SECP256R1:HITLS_EC_GROUP_SECP384R1"); ASSERT_TRUE(clientCtxConfig != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResult(serverRes), HITLS_SUCCESS); ASSERT_EQ(retry_count, 3); EXIT: HLT_FreeAllProcess(); retry_count = 0; } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_hlt_clienthello_cb.c
C
unknown
13,698
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "hlt.h" #include "logger.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "crypt_util_rand.h" #include "helper.h" #include "hitls.h" #include "frame_tls.h" #include "hitls_type.h" #include "rec_wrapper.h" #include "hs_ctx.h" #include "tls.h" /* END_HEADER */ #define READ_BUF_LEN_18K (18 * 1024) #define PORT 10087 static void Test_MultiKeyShare(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)bufSize; (void)user; (void)data; (void)*len; if (ctx->hsCtx->haveHrr) { *(bool *)user = true; } else { *(bool *)user = false; } return; } /* BEGIN_CASE */ void SDV_TLS13_MULTI_KEYSHARE_TC001() { bool haveHrr = false; HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); bool testHrr = true; RecWrapper wrapper = { TRY_SEND_FINISH, REC_TYPE_HANDSHAKE, false, &testHrr, Test_MultiKeyShare }; RegisterWrapper(wrapper); HLT_SetGroups(serverCtxConfig, "HITLS_EC_GROUP_SECP256R1"); HLT_SetGroups(clientCtxConfig, "X25519MLKEM768:HITLS_EC_GROUP_SECP256R1"); HLT_Tls_Res *serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Tls_Res *clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_EQ(testHrr, haveHrr); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HLT_FreeAllProcess(); ClearWrapper(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_hlt_multi_keyshare.c
C
unknown
3,027
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include "securec.h" #include "hlt.h" #include "logger.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "crypt_util_rand.h" #include "helper.h" #include "hitls.h" #include "frame_tls.h" #include "hitls_type.h" /* END_HEADER */ #define READ_BUF_LEN_18K (18 * 1024) #define PORT 10087 /* BEGIN_CASE */ void SDV_TLS13_PROVIDER_NEW_GROUP_SIGNALG_TC001(char *path, char *providerName, int providerLibFmt, char *group, char *signAlg, char *rootCa, char *interCa, char *serverCert, char *serverKey, char *clientCert, char *clientKey) { #ifndef HITLS_TLS_FEATURE_PROVIDER (void)path; (void)providerName; (void)providerLibFmt; (void)group; (void)signAlg; (void)rootCa; (void)interCa; (void)serverCert; (void)serverKey; (void)clientCert; (void)clientKey; SKIP_TEST(); #else HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetProviderPath(serverCtxConfig, path); HLT_SetProviderAttrName(serverCtxConfig, NULL); HLT_SetProviderPath(clientCtxConfig, path); HLT_SetProviderAttrName(clientCtxConfig, NULL); HLT_AddProviderInfo(serverCtxConfig, providerName, providerLibFmt); HLT_AddProviderInfo(serverCtxConfig, "default", BSL_SAL_LIB_FMT_OFF); HLT_AddProviderInfo(clientCtxConfig, providerName, providerLibFmt); HLT_AddProviderInfo(clientCtxConfig, "default", BSL_SAL_LIB_FMT_OFF); /* Set Cert */ HLT_SetCertPath(serverCtxConfig, rootCa, interCa, serverCert, serverKey, "NULL", "NULL"); HLT_SetCertPath(clientCtxConfig, rootCa, interCa, clientCert, clientKey, "NULL", "NULL"); HLT_SetGroups(serverCtxConfig, group); // For kex or kem group HLT_SetGroups(clientCtxConfig, group); // For kex or kem group HLT_SetSignature(serverCtxConfig, signAlg); HLT_SetSignature(clientCtxConfig, signAlg); HLT_SetCipherSuites(serverCtxConfig, "HITLS_AES_128_GCM_SHA256"); HLT_SetCipherSuites(clientCtxConfig, "HITLS_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HLT_FreeAllProcess(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS13_PROVIDER_KEM_TC001(char *group) { #ifndef HITLS_TLS_FEATURE_PROVIDER (void)group; SKIP_TEST(); #else HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetGroups(clientCtxConfig, group); // For kex or kem group HLT_SetGroups(serverCtxConfig, group); // For kex or kem group serverRes = HLT_ProcessTlsAccept(remoteProcess, TLS1_3, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(localProcess, TLS1_3, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(remoteProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(localProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HLT_FreeAllProcess(); #endif } /* END_CASE */ /* BEGIN_CASE */ void SDV_TLS13_MULTI_PROVIDER_TC001(char *path, char *providerName, char *attrName, int providerLibFmt) { #ifndef HITLS_TLS_FEATURE_PROVIDER (void)path; (void)providerName; (void)attrName; (void)providerLibFmt; SKIP_TEST(); #else (void)path; (void)providerName; (void)attrName; (void)providerLibFmt; HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Ctx_Config *serverCtxConfig = NULL; HLT_Ctx_Config *clientCtxConfig = NULL; HLT_Process *localProcess = HLT_InitLocalProcess(HITLS); HLT_Process *remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, PORT, true); ASSERT_TRUE(localProcess != NULL); ASSERT_TRUE(remoteProcess != NULL); serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetProviderPath(serverCtxConfig, path); HLT_SetProviderAttrName(serverCtxConfig, attrName); HLT_AddProviderInfo(serverCtxConfig, providerName, providerLibFmt); HLT_AddProviderInfo(serverCtxConfig, "default", BSL_SAL_LIB_FMT_OFF); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, TLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); clientRes = HLT_ProcessTlsConnect(remoteProcess, TLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[READ_BUF_LEN_18K] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, READ_BUF_LEN_18K, &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HLT_FreeAllProcess(); #endif } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_hlt_provider.c
C
unknown
7,616
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "hlt.h" #include "securec.h" #include "process.h" #include "session.h" #include "hitls_config.h" #include "hitls_crypt_init.h" /* END_HEADER */ #define READ_BUF_SIZE (18 * 1024) /** @ * @test SDV_TLS12_RESUME_FUNC_TC001 * @title Test the PSK-based session resume of tls12. * * @brief 1. at first handshake, config the client does not support tickets, but the server supports tickets. Expect result 1 2. after first handshake, config the client support tickets, Expect result 2 * @expect 1. connect success 2. resume success @ */ /* BEGIN_CASE */ void SDV_TLS12_RESUME_FUNC_TC001() { int version = TLS1_2; int connType = TCP; Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; HITLS_Session *session = NULL; int32_t cnt = 0; int32_t serverConfigId = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); clientCtxConfig->isSupportSessionTicket = false; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); serverCtxConfig->isSupportSessionTicket = true; HLT_SetPsk(clientCtxConfig, "123456789"); HLT_SetPsk(serverCtxConfig, "123456789"); #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); do { DataChannelParam channelParam; channelParam.port = 18889; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; if (cnt > 0) { clientCtxConfig->isSupportSessionTicket = true; ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); } int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); } if (cnt == 0) { ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); } else { int ret = HLT_TlsConnect(clientSsl); ASSERT_EQ(ret, HITLS_SUCCESS); uint8_t isReused = 0; ASSERT_TRUE(HITLS_IsSessionReused(clientSsl, &isReused) == HITLS_SUCCESS); ASSERT_EQ(isReused, 1); } ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_RpcTlsClose(remoteProcess, serverSslId); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); HITLS_SESS_Free(session); session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); cnt++; } while (cnt < 3); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */ /* @ * @test SDV_HITLS_TICKET_KEY_CALLBACK_RESUME_FUNC_TC001 * @spec - * @title Verifying the session resumption scenario after the session ticket key callback function is configured * @precon nan * @brief 1. The bottom-layer connection is established. 2. Register the session ticket key callback on the server. 3. After the first handshake is complete, obtain and store the session. 4. Configure the session in the SSL, resume the session, and obtain the session again. 5. Repeat step 4. Expected result 5 is obtained. * @expect 1. Return success 2. The registration is successful. 3. The handshake has completed and the session is obtained successfully. 4. The session is successfully configured, resumed, and obtained. 5. The session is successfully configured, resumed, and obtained. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void SDV_HITLS_TICKET_KEY_CALLBACK_RESUME_FUNC_TC001(int version, int connType, char *ticketKeyCb) { Process *localProcess = NULL; Process *remoteProcess = NULL; HLT_FD sockFd = {0}; int32_t serverConfigId = 0; HITLS_Session *session = NULL; const char *writeBuf = "Hello world"; uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; int32_t cnt = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_CreateRemoteProcess(HITLS); ASSERT_TRUE(remoteProcess != NULL); void *clientConfig = HLT_TlsNewCtx(version); ASSERT_TRUE(clientConfig != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); clientCtxConfig->isSupportSessionTicket = true; clientCtxConfig->isSupportRenegotiation = false; HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); serverCtxConfig->isSupportSessionTicket = true; serverCtxConfig->isSupportRenegotiation = false; #ifdef HITLS_TLS_FEATURE_PROVIDER serverConfigId = HLT_RpcProviderTlsNewCtx(remoteProcess, version, false, NULL, NULL, NULL, 0, NULL); #else serverConfigId = HLT_RpcTlsNewCtx(remoteProcess, version, false); #endif memcpy_s(clientCtxConfig->psk, PSK_MAX_LEN, "12121212121212", sizeof("12121212121212")); memcpy_s(serverCtxConfig->psk, PSK_MAX_LEN, "12121212121212", sizeof("12121212121212")); // Register the session ticket key callback on the server. HLT_SetTicketKeyCb(serverCtxConfig, ticketKeyCb); ASSERT_TRUE(HLT_TlsSetCtx(clientConfig, clientCtxConfig) == 0); ASSERT_TRUE(HLT_RpcTlsSetCtx(remoteProcess, serverConfigId, serverCtxConfig) == 0); HLT_SetCipherSuites(clientCtxConfig, "HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"); do { DataChannelParam channelParam; channelParam.port = 18899; channelParam.type = connType; channelParam.isBlock = true; sockFd = HLT_CreateDataChannel(localProcess, remoteProcess, channelParam); ASSERT_TRUE((sockFd.srcFd > 0) && (sockFd.peerFd > 0)); remoteProcess->connFd = sockFd.peerFd; localProcess->connFd = sockFd.srcFd; remoteProcess->connType = connType; localProcess->connType = connType; int32_t serverSslId = HLT_RpcTlsNewSsl(remoteProcess, serverConfigId); HLT_Ssl_Config *serverSslConfig; serverSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(serverSslConfig != NULL); serverSslConfig->sockFd = remoteProcess->connFd; serverSslConfig->connType = connType; ASSERT_TRUE(HLT_RpcTlsSetSsl(remoteProcess, serverSslId, serverSslConfig) == 0); HLT_RpcTlsAccept(remoteProcess, serverSslId); void *clientSsl = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientSsl != NULL); HLT_Ssl_Config *clientSslConfig; clientSslConfig = HLT_NewSslConfig(NULL); ASSERT_TRUE(clientSslConfig != NULL); clientSslConfig->sockFd = localProcess->connFd; clientSslConfig->connType = connType; // The bottom-layer connection is established. HLT_TlsSetSsl(clientSsl, clientSslConfig); if (session != NULL) { // Configure the session in the SSL, resume the session, and obtain the session again. ASSERT_TRUE(HITLS_SetSession(clientSsl, session) == HITLS_SUCCESS); } ASSERT_TRUE(HLT_TlsConnect(clientSsl) == 0); ASSERT_TRUE(HLT_RpcTlsWrite(remoteProcess, serverSslId, (uint8_t *)writeBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(memset_s(readBuf, READ_BUF_SIZE, 0, READ_BUF_SIZE) == EOK); ASSERT_TRUE(HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen) == 0); ASSERT_TRUE(readLen == strlen(writeBuf)); ASSERT_TRUE(memcmp(writeBuf, readBuf, strlen(writeBuf)) == 0); ASSERT_TRUE(HLT_RpcTlsClose(remoteProcess, serverSslId) == 0); ASSERT_TRUE(HLT_TlsClose(clientSsl) == 0); HLT_TlsRead(clientSsl, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcTlsRead(remoteProcess, serverSslId, readBuf, READ_BUF_SIZE, &readLen); HLT_RpcCloseFd(remoteProcess, sockFd.peerFd, remoteProcess->connType); HLT_CloseFd(sockFd.srcFd, localProcess->connType); if (cnt != 0) { if (strcmp(ticketKeyCb, "ExampleTicketKeyRenewCb") == 0) { SESS_Disable(session); } HITLS_SESS_Free(session); session = NULL; uint8_t isReused = 0; ASSERT_TRUE(HITLS_IsSessionReused(clientSsl, &isReused) == HITLS_SUCCESS); ASSERT_TRUE(isReused == 1); } // After the first handshake is complete, obtain and store the session. session = HITLS_GetDupSession(clientSsl); ASSERT_TRUE(session != NULL); ASSERT_TRUE(HITLS_SESS_HasTicket(session) == true); ASSERT_TRUE(HITLS_SESS_IsResumable(session) == true); cnt++; } while (cnt < 3); EXIT: HITLS_SESS_Free(session); HLT_FreeAllProcess(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/feature/test_suite_sdv_hlt_session_ticket.c
C
unknown
10,854
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <sys/types.h> #include <regex.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/select.h> #include <sys/time.h> #include <linux/ioctl.h> #include "securec.h" #include "bsl_sal.h" #include "sal_net.h" #include "frame_tls.h" #include "cert_callback.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "frame_io.h" #include "uio_abstraction.h" #include "tls.h" #include "tls_config.h" #include "logger.h" #include "process.h" #include "hs_ctx.h" #include "hlt.h" #include "stub_replace.h" #include "hitls_type.h" #include "frame_link.h" #include "session_type.h" #include "common_func.h" #include "hitls_func.h" #include "hitls_cert_type.h" #include "cert_mgr_ctx.h" #include "parser_frame_msg.h" #include "recv_process.h" #include "simulate_io.h" #include "rec_wrapper.h" #include "cipher_suite.h" #include "alert.h" #include "conn_init.h" #include "pack.h" #include "send_process.h" #include "cert.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "hs.h" #include "hs_state_recv.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "frame_msg.h" #include "pack_frame_msg.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "sctp_channel.h" #include "hitls_crypt_init.h" #include "hitls_session.h" #include "bsl_log.h" #include "bsl_err.h" #include "hitls_crypt_reg.h" #include "crypt_errno.h" #include "bsl_list.h" #include "hitls_cert.h" #include "parse_extensions_client.c" #include "parse_extensions_server.c" #include "parse_server_hello.c" #include "parse_client_hello.c" /* END_HEADER */ static char *g_serverName = "testServer"; uint32_t g_uiPort = 18888; #define DEFAULT_DESCRIPTION_LEN 128 #define TLS_DHE_PARAM_MAX_LEN 1024 #define GET_GROUPS_CNT (-1) #define READ_BUF_SIZE (18 * 1024) #define ALERT_BODY_LEN 2u typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; HITLS_TicketKeyCb serverKeyCb; } ResumeTestInfo; int32_t HITLS_RemoveCertAndKey(HITLS_Ctx *ctx); HITLS_CRYPT_Key *cert_key = NULL; HITLS_CRYPT_Key *DH_CB(HITLS_Ctx *ctx, int32_t isExport, uint32_t keyLen) { (void)ctx; (void)isExport; (void)keyLen; return cert_key; } void *STUB_SAL_Calloc(uint32_t num, uint32_t size) { (void)num; (void)size; return NULL; } void *STUB_SAL_Dump(const void *src, uint32_t size) { (void)src; (void)size; return NULL; } FuncStubInfo g_TmpRpInfo = {0}; int32_t STUB_BSL_UIO_Read(BSL_UIO *uio, void *data, uint32_t len, uint32_t *readLen) { (void)uio; (void)data; (void)len; (void)readLen; return 0; } static HITLS_Config *GetHitlsConfigViaVersion(int ver) { switch (ver) { case HITLS_VERSION_TLS12: return HITLS_CFG_NewTLS12Config(); case HITLS_VERSION_TLS13: return HITLS_CFG_NewTLS13Config(); case HITLS_VERSION_DTLS12: return HITLS_CFG_NewDTLS12Config(); default: return NULL; } } /** @ * @test UT_TLS_CM_IS_DTLS_API_TC001 * @title Test HITLS_IsDtls * @precon nan * @brief HITLS_IsDtls * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer the non-empty TLS connection handle information and leave isDtls blank. Expected result 1. * 3. Transfer the non-empty TLS connection handle information. The isDtls parameter is not empty. Expected result 2 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CM_IS_DTLS_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint8_t isDtls = 0; ASSERT_TRUE(HITLS_IsHandShakeDone(ctx, &isDtls) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_IsHandShakeDone(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_IsHandShakeDone(ctx, &isDtls) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_CLEAR_CIPHERSUITES_API_TC001 * @title Test the HITLS_SetCipherSuites and HITLS_ClearTLS13CipherSuites interfaces. * @precon nan * @brief HITLS_SetCipherSuites * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer non-empty TLS connection handle information and leave cipherSuites empty. Expected result 1. * 3. Transfer the non-empty TLS connection handle information. If cipherSuites is not empty and cipherSuitesSize is 0, * the expected result is 1. * 4. Transfer the non-empty TLS connection handle information. Set cipherSuites to a value greater than * HITLS_CFG_MAX_SIZE. Expected result 2. * 5. The input parameters are valid, and the SAL_CALLOC table is instrumented. Expected result 3. * 6. Transfer the non-null TLS connection handle information, set cipherSuites to an invalid value, and set * cipherSuitesSize to a value smaller than HITLS_CFG_MAX_SIZE. Expected result 4 is displayed. * 7. Transfer valid parameters. Expected result 5. * HITLS_ClearTLS13CipherSuites * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer the non-empty TLS connection handle information. Expected result 5. * @expect 1. Returns HITLS_NULL_INPUT * 2. Return HITLS_HITLS_CM_INVALID_LENGTH * 3. Returns HITLS_MEMALLOC_FAIL * 4. Return HITLS_HITLS_CM_NO_SUITABLE_CIPHER_SUITE * 5. Returns HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_CLEAR_CIPHERSUITES_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint16_t cipherSuites[10] = { HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, }; ASSERT_TRUE(HITLS_SetCipherSuites(ctx, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_ClearTLS13CipherSuites(ctx) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetCipherSuites(ctx, NULL, 0) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetCipherSuites(ctx, cipherSuites, 0) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetCipherSuites(ctx, cipherSuites, HITLS_CFG_MAX_SIZE + 1) == HITLS_CONFIG_INVALID_LENGTH); STUB_Init(); FuncStubInfo tmpRpInfo; STUB_Replace(&tmpRpInfo, BSL_SAL_Calloc, STUB_SAL_Calloc); ASSERT_TRUE( HITLS_SetCipherSuites(ctx, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_MEMALLOC_FAIL); STUB_Reset(&tmpRpInfo); uint16_t cipherSuites2[10] = {0}; cipherSuites2[0] = 0xFFFF; cipherSuites2[1] = 0xEFFF; ASSERT_TRUE(HITLS_SetCipherSuites(ctx, cipherSuites2, sizeof(cipherSuites2) / sizeof(uint16_t)) == HITLS_CONFIG_NO_SUITABLE_CIPHER_SUITE); ASSERT_TRUE(HITLS_SetCipherSuites(ctx, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); if (tlsVersion == HITLS_VERSION_TLS13) { ASSERT_TRUE(HITLS_ClearTLS13CipherSuites(ctx) == HITLS_SUCCESS); ASSERT_TRUE(ctx->config.tlsConfig.tls13cipherSuitesSize == 0); } EXIT: STUB_Reset(&tmpRpInfo); HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_GET_ENCRYPTHENMAC_FUNC_TC001 * @title HITLS_GetEncryptThenMac and HITLS_SetEncryptThenMac interface validation * @precon nan * @brief * 1. After initialization, call the hitls_setencryptthenmac interface to set the value to true and call the * HITLS_GetEncryptThenMac interface to query the value. Expected result 1. * 2. Set hitls_setencryptthenmac to true at both ends. After the connection is set up, invoke the HITLS_GetEncryptThenMac * interface to query the connection. Expected result 2. * @expect * 1. The return value is true. * 2. The return value is true. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_ENCRYPTHENMAC_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); uint32_t encryptThenMacType = 0; ASSERT_EQ(HITLS_GetEncryptThenMac(server->ssl, &encryptThenMacType), HITLS_SUCCESS); ASSERT_EQ(encryptThenMacType, 1); ASSERT_EQ(HITLS_GetEncryptThenMac(client->ssl, &encryptThenMacType), HITLS_SUCCESS); ASSERT_EQ(encryptThenMacType, 1); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_EQ(HITLS_GetEncryptThenMac(server->ssl, &encryptThenMacType), HITLS_SUCCESS); ASSERT_EQ(encryptThenMacType, 1); ASSERT_EQ(HITLS_GetEncryptThenMac(client->ssl, &encryptThenMacType), HITLS_SUCCESS); ASSERT_EQ(encryptThenMacType, 1); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_SERVERNAME_FUNC_TC001 * @title HITLS_SetServerName invokes the interface to set the server name. * @precon nan * @brief * 1. Initialize the client and server. Expected result 1 * 2. After the initialization, set the servername and run the HITLS_GetServerName command to check the server name. * Expected result 2 is displayed * @expect * 1. Complete initialization * 2. The returned result is consistent with the settings @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_SERVERNAME_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetServerName(client->ssl, (uint8_t *)g_serverName, (uint32_t)strlen(g_serverName)), HITLS_SUCCESS); client->ssl->isClient = true; const char *server_name = HITLS_GetServerName(client->ssl, HITLS_SNI_HOSTNAME_TYPE); ASSERT_TRUE(memcmp(server_name, (uint8_t *)g_serverName, strlen(g_serverName)) == 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_SET_GET_SESSION_TICKET_SUPPORT_API_TC001 * @title Test the HITLS_SetSessionTicketSupport and HITLS_GetSessionTicketSupport interfaces. * @precon nan * @brief HITLS_SetSessionTicketSupport * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set isEnable to an invalid value. Expected result 2. * 3. Transfer the non-empty TLS connection handle information and set isEnable to a valid value. Expected result 3 is * obtained. * HITLS_GetSessionTicketSupport * 1. Input an empty TLS connection handle. Expected result 1. * 2. Pass an empty getIsSupport pointer. Expected result 1. * 3. Transfer the non-null TLS connection handle information and ensure that the getIsSupport pointer is not null. * Expected result 3. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and ctx->config.tlsConfig.isSupportSessionTicket is true. * 3. Returns HITLS_SUCCES and ctx->config.tlsConfig.isSupportSessionTicket is true or false. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_SESSION_TICKET_SUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint8_t isSupport = -1; uint8_t getIsSupport = -1; ASSERT_TRUE(HITLS_SetSessionTicketSupport(ctx, isSupport) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetSessionTicketSupport(ctx, &getIsSupport) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetSessionTicketSupport(ctx, NULL) == HITLS_NULL_INPUT); isSupport = 1; ASSERT_TRUE(HITLS_SetSessionTicketSupport(ctx, isSupport) == HITLS_SUCCESS); isSupport = -1; ASSERT_TRUE(HITLS_SetSessionTicketSupport(ctx, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(ctx->config.tlsConfig.isSupportSessionTicket = true); isSupport = 0; ASSERT_TRUE(HITLS_SetSessionTicketSupport(ctx, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetSessionTicketSupport(ctx, &getIsSupport) == HITLS_SUCCESS); ASSERT_TRUE(getIsSupport == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CM_VERIFY_CLIENT_POST_HANDSHAKE_API_TC001 * @title Invoke the HITLS_VerifyClientPostHandshake interface during connection establishment. * @precon nan * @brief * 1. Apply for and initialize the configuration file. Expected result 1. * 2. Configure the client and server to support post-handshake extension. Expected result 3. * 3. When a connection is established, the server is in the Try_RECV_CLIENT_HELLO state, and the * HITLS_VerifyClientPostHandshake interface is invoked. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. The interface fails to be invoked. @ */ /* BEGIN_CASE */ void UT_TLS_CM_VERIFY_CLIENT_POST_HANDSHAKE_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; // Apply for and initialize the configuration file config = HITLS_CFG_NewTLS13Config(); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); // Configure the client and server to support post-handshake extension client->ssl->config.tlsConfig.isSupportPostHandshakeAuth = true; server->ssl->config.tlsConfig.isSupportPostHandshakeAuth = true; ASSERT_TRUE(client->ssl->config.tlsConfig.isSupportPostHandshakeAuth == true); ASSERT_TRUE(server->ssl->config.tlsConfig.isSupportPostHandshakeAuth == true); // he server is in the Try_RECV_CLIENT_HELLO state ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_RECV_CLIENT_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(server->ssl->hsCtx->state == TRY_RECV_CLIENT_HELLO); // the HITLS_VerifyClientPostHandshake interface is invoked ASSERT_EQ(HITLS_VerifyClientPostHandshake(client->ssl), HITLS_INVALID_INPUT); ASSERT_EQ(HITLS_VerifyClientPostHandshake(server->ssl), HITLS_MSG_HANDLE_STATE_ILLEGAL); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_REMOVE_CERTANDKEY_API_TC001 * @title Test the HITLS_RemoveCertAndKey interface. * @brief * 1. Apply for and initialize the configuration file. Expected result 1. * 2. Invoke the client HITLS_CFG_SetClientVerifySupport and HITLS_CFG_SetNoClientCertSupport. Expected result 2. * 3. Invoke the HITLS_RemoveCertAndKey, Expected result 3. * @expect * 1. The initialization is successful. * 2. The setting is successful. * 3. Return HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CM_REMOVE_CERTANDKEY_API_TC001(void) { FRAME_Init(); int32_t ret; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); ret = HITLS_CFG_SetClientVerifySupport(config, true); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_CFG_SetNoClientCertSupport(config, true); ASSERT_TRUE(ret == HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(server != NULL); ret = HITLS_RemoveCertAndKey(client->ssl); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = FRAME_CreateConnection(client, server, false, HS_STATE_BUTT); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(server->ssl->state == CM_STATE_TRANSPORTING); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ static int32_t TestHITLS_PasswordCb(char *buf, int32_t bufLen, int32_t flag, void *userdata) { (void)buf; (void)bufLen; (void)flag; (void)userdata; return 0; } /* @ * @test UT_TLS_CM_SET_GET_DEFAULT_API_TC001 * @title Test HITLS_SetDefaultPasswordCb/HITLS_GetDefaultPasswordCb interface * @brief 1. Invoke the HITLS_SetDefaultPasswordCb interface. Expected result 1. * 2. Invoke the HITLS_SetDefaultPasswordCb interface. The value of ctx is not empty and the value of password is * not empty. Expected result 3. * 3. Invoke the HITLS_GetDefaultPasswordCb interface and leave ctx blank. Expected result 2. * @expect 1. Returns HITLS_NULL_INPUT * 2. NULL is returned. * 3. HITLS_SUCCESS is returned. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_DEFAULT_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = GetHitlsConfigViaVersion(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetDefaultPasswordCb(NULL, TestHITLS_PasswordCb) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetDefaultPasswordCb(ctx, TestHITLS_PasswordCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetDefaultPasswordCb(NULL) == NULL); ASSERT_TRUE(HITLS_GetDefaultPasswordCb(ctx) == TestHITLS_PasswordCb); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_GET_SESSION_API_TC001 * @title Test HITLS_SetSession/HITLS_GetSession interface * @brief 1. If ctx is NULL, Invoke the HITLS_SetSession interface.Expected result 1. * 2. Invoke the HITLS_SetSession interface.Expected result 2. * 3. Invoke the HITLS_GetSession interface. Expected result 2. * @expect 1. Returns HITLS_NULL_INPUT * 2. returnes HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_SESSION_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = GetHitlsConfigViaVersion(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetSession(NULL, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetSession(ctx, NULL) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetSession(ctx) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_PEERSIGNATURE_TYPE_API_TC001 * @title Test HITLS_GetPeerSignatureType interface * @brief 1. If ctx is NULL, Invoke the HITLS_GetPeerSignatureType interface. Expected result 2. * 2. Invoke the HITLS_GetPeerSignatureType interface. Expected result 1. * @expect 1. Returns HITLS_CONFIG_NO_SUITABLE_CIPHER_SUITE * 2.Returns HITLS_NULL_INPUT @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_PEERSIGNATURE_TYPE_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = GetHitlsConfigViaVersion(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); HITLS_SignAlgo sigType = {0}; ASSERT_EQ(HITLS_GetPeerSignatureType(NULL, NULL), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_GetPeerSignatureType(ctx, &sigType), HITLS_CONFIG_NO_SUITABLE_CIPHER_SUITE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ static void Test_Fatal_Alert(HITLS_Ctx *ctx, uint8_t *data, uint32_t *len, uint32_t bufSize, void *user) { (void)bufSize; (void)user; (void)len; (void)data; uint8_t alertdata[2] = {0x02, 0x29}; REC_Write(ctx, REC_TYPE_ALERT, alertdata, 2); return; } /** @ * @test UT_TLS_CM_FATAL_ALERT_TC001 * @title recv fatal alert brefore client hello need to close connection * @precon nan * @brief 1. Initialize the client and server. Expected result 1 * 2. After the initialization, send a fetal alert to server, expect reslut 2. * @expect 1. The initialization is successful. * 2. The client close the connection @ */ /* BEGIN_CASE */ void UT_TLS_CM_FATAL_ALERT_TC001(int version) { RecWrapper wrapper = { TRY_SEND_CLIENT_HELLO, REC_TYPE_HANDSHAKE, false, NULL, Test_Fatal_Alert }; RegisterWrapper(wrapper); FRAME_Init(); HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); /* Link initialization */ client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(client->ssl->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_EQ(server->ssl->state, CM_STATE_ALERTED); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); /* Alert recv means the handshake state is in alerting state and no alert to be sent*/ ASSERT_EQ(info.flag, ALERT_FLAG_RECV); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_NO_CERTIFICATE_RESERVED); EXIT: ClearWrapper(); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); return; } /* END_CASE */ /* @ * @test UT_TLS_GET_GLOBALCONFIG_TC001 * @spec - * @title test for HITLS_GetGlobalConfig * @precon nan * @brief HITLS_GetGlobalConfig * 1. Transfer an empty TLS connection handle. Expected result 1 is obtained * 2. Transfer non-empty TLS connection handle information. Expected result 2 is obtained * @expect 1. return NULL * 2. return globalConfig of TLS context @ */ /* BEGIN_CASE */ void UT_TLS_GET_GLOBALCONFIG_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; ASSERT_TRUE(HITLS_GetGlobalConfig(ctx) == NULL); config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetGlobalConfig(ctx) != NULL); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_HITLS_PEEK_TC001 * @brief 1. Establish connection between server and client 2. client sends a byte 3. server calls HITLS_Peek twice 4. server calls HITLS_Read to read one byte to make IO empty 5. server calls HITLS_Peek * @expect 1. Return HITLS_SUCCESS 2. Return HITLS_SUCCESS 3. Return HITLS_SUCCESS 4. Return HITLS_SUCCESS 5. Return HITLS_REC_NORMAL_RECV_BUF_EMPTY @ */ /* BEGIN_CASE */ void UT_TLS_HITLS_PEEK_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint8_t c2s[] = {0}; uint32_t writeLen; ASSERT_TRUE(HITLS_Write(client->ssl, c2s, sizeof(c2s), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t peekBuf[8] = {0}; uint8_t peekBuf1[8] = {0}; uint8_t peekBuf2[8] = {0}; uint8_t readBuf[8] = {0}; uint32_t peekLen = 0; uint32_t peekLen1 = 0; uint32_t peekLen2 = 0; uint32_t readLen = 0; ASSERT_EQ(HITLS_Peek(server->ssl, peekBuf, sizeof(peekBuf), &peekLen), HITLS_SUCCESS); ASSERT_EQ(peekLen, sizeof(c2s)); ASSERT_EQ(memcmp(peekBuf, c2s, peekLen), 0); ASSERT_EQ(HITLS_Peek(server->ssl, peekBuf1, sizeof(peekBuf1), &peekLen1), HITLS_SUCCESS); ASSERT_EQ(peekLen1, sizeof(c2s)); ASSERT_EQ(memcmp(peekBuf1, c2s, peekLen1), 0); ASSERT_EQ(HITLS_Read(server->ssl, readBuf, sizeof(readBuf), &readLen), HITLS_SUCCESS); ASSERT_EQ(readLen, sizeof(c2s)); ASSERT_EQ(memcmp(readBuf, c2s, readLen), 0); ASSERT_EQ(HITLS_Peek(server->ssl, peekBuf2, sizeof(peekBuf2), &peekLen2), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_EQ(peekLen2, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_SetTmpDhCb_TC001 * @spec - * @title HITLS_SetTmpDhCb interface test. The config field is empty. * @precon nan * @brief 1. If config is empty, expected result 1 occurs. * @expect 1. HITLS_NULL_INPUT is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_SetTmpDhCb_TC001(void) { // config is empty ASSERT_TRUE(HITLS_SetTmpDhCb(NULL, DH_CB) == HITLS_NULL_INPUT); EXIT: ; } /* END_CASE */ /** @ * @test UT_TLS_SET_VERSION_API_TC001 * @title Overwrite the input parameter of the HITLS_SetVersion interface. * @precon nan * @brief 1. Invoke the HITLS_SetVersion interface and leave ctx blank. Expected result 2 . * 2. Invoke the HITLS_SetVersion interface. The ctx parameter is not empty. The minimum version number is * DTLS1.0, and the maximum version number is DTLS1.2. Expected result 2 . * 3. Invoke the HITLS_SetVersion interface. The ctx parameter is not empty, the minimum version number is * DTLS1.2, and the maximum version number is DTLS1.2. Expected result 1 . * 4. Invoke the HITLS_SetVersion interface, set ctx to a value, set the minimum version number to DTLS1.2, and * set the maximum version number to DTLS1.0. Expected result 2 . * 5. Invoke the HITLS_SetVersion interface, set ctx to a value, set the minimum version number to DTLS1.2, and * set the maximum version number to TLS1.0. (Expected result 2) * 6. Invoke the HITLS_SetVersion interface, set ctx to a value, set the minimum version number to DTLS1.2, and * set the maximum version number to TLS1.2. Expected result 2 . * 7. Invoke the HITLS_SetVersion interface, set ctx to a value, set the minimum version number to TLS1.0, and set * the maximum version number to DTLS1.2. Expected result 2 . * 8. Invoke the HITLS_SetVersion interface, set ctx to a value, set the minimum version number to TLS1.2, and set * the maximum version number to DTLS1.2. Expected result 2 . * @expect 1. The interface returns a success response, HITLS_SUCCESS. * 2. The interface returns an error code. @ */ /* BEGIN_CASE */ void UT_TLS_SET_VERSION_API_TC001(void) { HitlsInit(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); int32_t ret; ret = HITLS_SetVersion(NULL, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12); ASSERT_TRUE(ret != HITLS_SUCCESS); ret = HITLS_SetVersion(ctx, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_SetVersion(ctx, HITLS_VERSION_DTLS12, HITLS_VERSION_TLS12); ASSERT_TRUE(ret != HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_SET_ServerName_TC001 * @spec - * @title HITLS_SetServerName invokes the interface to set the server name. * @precon nan * @brief 1. Initialize the client and server. Expected result 1 2. After the initialization, set the servername and run the HITLS_GetServerName command to check the server name. Expected result 2 is displayed * @expect 1. Complete initialization 2. The returned result is consistent with the settings * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_SET_ServerName_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_SetServerName(client->ssl, (uint8_t *)g_serverName, (uint32_t)strlen((char *)g_serverName)), HITLS_SUCCESS); client->ssl->isClient = true; const char *server_name = HITLS_GetServerName(client->ssl, HITLS_SNI_HOSTNAME_TYPE); ASSERT_TRUE(memcmp(server_name, g_serverName, strlen(g_serverName)) == 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_REQUEST) == HITLS_SUCCESS); server_name = HS_GetServerName(server->ssl); ASSERT_TRUE(memcmp(server_name, g_serverName, strlen(g_serverName)) == 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test The interface is invoked in the Idle state. An exception is returned. * @spec - * @title UT_TLS_HITLS_READ_WRITE_TC001 * @precon nan * @brief 1. When the connection is in the Idle state, call the hitls_read/hitls_write interface. Expected result 1 is obtained. * @expect 1. The connection is not established. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_HITLS_READ_WRITE_TC001(int version) { FRAME_Init(); HITLS_Config *config = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(client->ssl->state == CM_STATE_IDLE); ASSERT_TRUE(server->ssl->state == CM_STATE_IDLE); // 1. When the link is in the Idle state, call the hitls_read/hitls_write interface. uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readLen) == HITLS_CM_LINK_UNESTABLISHED); ASSERT_TRUE(HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen) == HITLS_CM_LINK_UNESTABLISHED); // 1. When the link is in the Idle state, call the hitls_read/hitls_write interface. uint8_t writeBuf[] = "abc"; uint32_t writeLen = 4; uint32_t len = 0; ASSERT_TRUE(HITLS_Write(client->ssl, writeBuf, writeLen, &len) == HITLS_CM_LINK_UNESTABLISHED); ASSERT_TRUE(HITLS_Write(server->ssl, writeBuf, writeLen, &len) == HITLS_CM_LINK_UNESTABLISHED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test test HITLS_Close in different cm state * @spec - * @title UT_TLS_HITLS_CLOSE_TC001 * @precon nan * @brief 1. Initialize the client and server. Expected result 1 2. Invoke HITLS_Connect to send the message. Expected result 2 3. Invoke HITLS_Close and failed to send the message. Expected result 3 4. Succeeded in invoking HITLS_Connect to resend the failed close_notify message. Expected result 4 5. Invoke HITLS_Close to send the message. Expected result 5 * @expect 1. The connection is not established. 2. The client status is CM_STATE_HANDSHAKING. 3. The client status is CM_STATE_ALERTING. 4. The client status is CM_STATE_ALERTED. 5. The client status is CM_STATE_CLOSED. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_HITLS_CLOSE_TC001(int uioType) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; FRAME_Msg recvframeMsg = {0}; FRAME_Msg sndframeMsg = {0}; config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, uioType); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, uioType); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_REQUEST) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->hsCtx->state == TRY_RECV_CERTIFICATE_REQUEST); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(client->io); ioUserData->sndMsg.len = 1; ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_REC_NORMAL_IO_BUSY); ASSERT_EQ(clientTlsCtx->state, CM_STATE_ALERTED); ioUserData->sndMsg.len = 0; ASSERT_EQ(HITLS_Close(clientTlsCtx), HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); EXIT: CleanRecordBody(&recvframeMsg); CleanRecordBody(&sndframeMsg); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test test HITLS_Close in different cm state * @spec - * @title UT_TLS_HITLS_CLOSE_TC002 * @precon nan * @brief 1. Initialize the client and server. Expected result 1 2. Invoke HITLS_Close. Expected result 2 * @expect 1. The connection is not established. 2. The client status is CM_STATE_CLOSED. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_HITLS_CLOSE_TC002(int uioType) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); client = FRAME_CreateLink(config, uioType); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, uioType); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(HITLS_Close(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_CLOSED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ int32_t ParseServerCookie(ParsePacket *pkt, ServerHelloMsg *msg); /* @ * @test test ParseServerCookie and ParseClientCookie * @spec - * @title UT_TLS_PARSE_Cookie_TC001 * @precon nan * @brief 1. Initialize the client. Expected result 1 2. Assemble a message with zero length cookie, invoke ParseServerCookie. Expected result 2 3. Assemble a message with zero length cookie, invoke ParseClientCookie. Expected result 2 * @expect 1. The connection is not established. 2. The return value is HITLS_PARSE_INVALID_MSG_LEN. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_PARSE_Cookie_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); CONN_Init(client->ssl); ServerHelloMsg svrMsg = { 0 }; ClientHelloMsg cliMsg = { 0 }; uint8_t cookie[] = { 0x00 }; uint32_t bufOffset = 0; ParsePacket pkt = {.ctx = client->ssl, .buf = cookie, .bufLen = sizeof(cookie), .bufOffset = &bufOffset}; ASSERT_EQ(ParseServerCookie(&pkt, &svrMsg), HITLS_PARSE_INVALID_MSG_LEN); CleanServerHello(&svrMsg); ASSERT_EQ(ParseClientCookie(&pkt, &cliMsg), HITLS_PARSE_INVALID_MSG_LEN); CleanClientHello(&cliMsg); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface/test_suite_sdv_frame_tls_cm_1.c
C
unknown
37,949
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <sys/types.h> #include <regex.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/select.h> #include <sys/time.h> #include <linux/ioctl.h> #include "securec.h" #include "bsl_sal.h" #include "sal_net.h" #include "hitls.h" #include "frame_tls.h" #include "cert_callback.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "frame_io.h" #include "uio_abstraction.h" #include "tls.h" #include "tls_config.h" #include "logger.h" #include "process.h" #include "hs_ctx.h" #include "hlt.h" #include "stub_replace.h" #include "hitls_type.h" #include "frame_link.h" #include "session_type.h" #include "common_func.h" #include "hitls_func.h" #include "hitls_cert_type.h" #include "cert_mgr_ctx.h" #include "parser_frame_msg.h" #include "recv_process.h" #include "simulate_io.h" #include "rec_wrapper.h" #include "cipher_suite.h" #include "alert.h" #include "conn_init.h" #include "pack.h" #include "send_process.h" #include "cert.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "hs.h" #include "hs_state_recv.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "frame_msg.h" #include "pack_frame_msg.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "sctp_channel.h" #include "hitls_crypt_init.h" #include <stdlib.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_log.h" #include "bsl_err.h" #include "bsl_uio.h" #include "hitls_crypt_reg.h" #include "hitls_session.h" #include "cert_method.h" #include "bsl_list.h" #include "session_mgr.h" #include "hitls_x509_verify.h" #define DEFAULT_DESCRIPTION_LEN 128 #define ERROR_HITLS_GROUP 1 #define ERROR_HITLS_SIGNATURE 0xffffu typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; /* Set the session to the client for session resume. */ } ResumeTestInfo; HITLS_CERT_X509 *HiTLS_X509_LoadCertFile(HITLS_Config *tlsCfg, const char *file); void SAL_CERT_X509Free(HITLS_CERT_X509 *cert); static HITLS_Config *GetHitlsConfigViaVersion(int ver) { switch (ver) { case TLS1_2: case HITLS_VERSION_TLS12: return HITLS_CFG_NewTLS12Config(); case TLS1_3: case HITLS_VERSION_TLS13: return HITLS_CFG_NewTLS13Config(); case DTLS1_2: case HITLS_VERSION_DTLS12: return HITLS_CFG_NewDTLS12Config(); default: return NULL; } } int32_t Stub_Write(BSL_UIO *uio, const void *buf, uint32_t len, uint32_t *writeLen) { (void)uio; (void)buf; (void)len; (void)writeLen; return HITLS_SUCCESS; } int32_t Stub_Read(BSL_UIO *uio, void *buf, uint32_t len, uint32_t *readLen) { (void)uio; (void)buf; (void)len; (void)readLen; return HITLS_SUCCESS; } int32_t Stub_Ctrl(BSL_UIO *uio, BSL_UIO_CtrlParameter cmd, void *param) { (void)uio; (void)cmd; (void)param; return HITLS_SUCCESS; } /* END_HEADER */ /** @ * @test UT_TLS_CFG_SET_VERSION_API_TC001 * @title Overwrite the input parameter of the HITLS_CFG_SetVersion interface. * @precon nan * @brief 1. Invoke the HITLS_CFG_SetVersion interface and leave config blank. Expected result 2 . * 2. Invoke the HITLS_CFG_SetVersion interface. The config parameter is not empty. The minimum version number is * DTLS1.0, and the maximum version number is DTLS1.2. Expected result 2 . * 3. Invoke the HITLS_CFG_SetVersion interface. The config parameter is not empty, the minimum version number is * DTLS1.2, and the maximum version number is DTLS1.2. Expected result 1 . * 4. Invoke the HITLS_CFG_SetVersion interface, set config to a value, set the minimum version number to DTLS1.2, and * set the maximum version number to DTLS1.0. Expected result 2 . * 5. Invoke the HITLS_CFG_SetVersion interface, set config to a value, set the minimum version number to DTLS1.2, and * set the maximum version number to TLS1.0. (Expected result 2) * 6. Invoke the HITLS_CFG_SetVersion interface, set config to a value, set the minimum version number to DTLS1.2, and * set the maximum version number to TLS1.2. Expected result 2 . * 7. Invoke the HITLS_CFG_SetVersion interface, set config to a value, set the minimum version number to TLS1.0, and set * the maximum version number to DTLS1.2. Expected result 2 . * 8. Invoke the HITLS_CFG_SetVersion interface, set config to a value, set the minimum version number to TLS1.2, and set * the maximum version number to DTLS1.2. Expected result 2 . * @expect 1. The interface returns a success response, HITLS_SUCCESS. * 2. The interface returns an error code. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_VERSION_API_TC001(void) { HitlsInit(); HITLS_Config *tlsConfig = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); int32_t ret; ret = HITLS_CFG_SetVersion(NULL, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12); ASSERT_TRUE(ret != HITLS_SUCCESS); ret = HITLS_CFG_SetVersion(tlsConfig, HITLS_VERSION_DTLS10, HITLS_VERSION_DTLS12); ASSERT_TRUE(ret != HITLS_SUCCESS); ret = HITLS_CFG_SetVersion(tlsConfig, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_CFG_SetVersion(tlsConfig, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS10); ASSERT_TRUE(ret != HITLS_SUCCESS); ret = HITLS_CFG_SetVersion(tlsConfig, HITLS_VERSION_DTLS12, HITLS_VERSION_TLS10); ASSERT_TRUE(ret != HITLS_SUCCESS); ret = HITLS_CFG_SetVersion(tlsConfig, HITLS_VERSION_DTLS12, HITLS_VERSION_TLS12); ASSERT_TRUE(ret != HITLS_SUCCESS); ret = HITLS_CFG_SetVersion(tlsConfig, HITLS_VERSION_TLS10, HITLS_VERSION_DTLS12); ASSERT_TRUE(ret != HITLS_SUCCESS); ret = HITLS_CFG_SetVersion(tlsConfig, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12); ASSERT_TRUE(ret != HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_VERSIONFORBID_API_TC001 * @title Test the HITLS_CFG_SetVersionForbid interface. * @precon nan * @brief HITLS_CFG_SetVersionForbid * 1. Import empty configuration information. Expected result 1. * 2. Transfer non-empty configuration information and set version to an invalid value. Expected result 2. * 3. Transfer non-empty configuration information and set version to a valid value. Expected result 3. * 4. Use HITLS_CFG_GetVersionSupport to view the result. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned, and invalid values in config are filtered out. * 3. HITLS_SUCCES is returned and config is the expected value. * 4. The HITLS_SUCCES parameter is returned, and the version parameter is set to the value recorded in the config file. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_VERSIONFORBID_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; uint32_t version = TLS12_VERSION_BIT; ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config, version) == HITLS_NULL_INPUT); version = 0; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS12_VERSION_BIT); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS12); HITLS_CFG_FreeConfig(config); config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS_VERSION_MASK); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); HITLS_CFG_FreeConfig(config); config = HITLS_CFG_NewTLS12Config(); version = HITLS_VERSION_TLS12; ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS12_VERSION_BIT); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS12); version = HITLS_VERSION_DTLS12; ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS12_VERSION_BIT); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS12); version = 0x0305u; ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS12_VERSION_BIT); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS12); HITLS_CFG_FreeConfig(config); config = HITLS_CFG_NewTLSConfig(); version = HITLS_VERSION_DTLS12; ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS_VERSION_MASK); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); version = 0x0305u; ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS_VERSION_MASK); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); HITLS_CFG_FreeConfig(config); config = HITLS_CFG_NewTLSConfig(); version = HITLS_VERSION_TLS13; ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS12_VERSION_BIT); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS12); HITLS_CFG_FreeConfig(config); config = HITLS_CFG_NewTLSConfig(); version = HITLS_TLS_ANY_VERSION; ASSERT_TRUE(HITLS_CFG_SetVersionForbid(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->version == TLS_VERSION_MASK); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_EXTENEDMASTERSECRETSUPPORT_API_TC001 * @spec - * @title Test the HITLS_CFG_SetExtenedMasterSecretSupport and HITLS_CFG_GetExtenedMasterSecretSupport interfaces. * @precon nan * @brief HITLS_CFG_SetExtenedMasterSecretSupport * 1. Import empty configuration information. Expected result 1. * 2. Transfer non-empty configuration information and set support to an invalid value. Expected result 2. * 3. Transfer non-empty configuration information and set support to a valid value. Expected result 3. * HITLS_CFG_GetExtenedMasterSecretSupport * 1. Import empty configuration information. Expected result 1. * 2. Transfer an empty isSupport pointer. Expected result 1. * 3. Transfer the non-null configuration information and the isSupport pointer is not null. Expected result 3 is * obtained. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and config->isSupportExtendMasterSecret is true. * 3. Returns HITLS_SUCCES and config->isSupportExtendMasterSecret is true or false. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_EXTENEDMASTERSECRETSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_CFG_SetExtenedMasterSecretSupport(config, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetExtenedMasterSecretSupport(config, &isSupport) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetExtenedMasterSecretSupport(config, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_CFG_SetExtenedMasterSecretSupport(config, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_CFG_SetExtenedMasterSecretSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetExtenedMasterSecretSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_CFG_SetExtenedMasterSecretSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetExtenedMasterSecretSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_POSTHANDSHAKEAUTHSUPPORT_API_TC001 * @spec - * @titleTest the HITLS_CFG_SetPostHandshakeAuthSupport and HITLS_CFG_GetPostHandshakeAuthSupport interfaces. * @precon nan * @brief HITLS_CFG_SetPostHandshakeAuthSupport * 1. Import empty configuration information. Expected result 1. * 2. Transfer non-empty configuration information and set support to an invalid value. Expected result 2. * 3. Transfer non-empty configuration information and set support to a valid value. Expected result 3. * HITLS_CFG_GetPostHandshakeAuthSupport * 1. Import empty configuration information. Expected result 1. * 2. Transfer an empty isSupport pointer. Expected result 1. * 3. Transfer the non-null configuration information and the isSupport pointer is not null. Expected result 3 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and the value of config->isSupportPostHandshakeAuth is true. * 3. HITLS_SUCCES is returned and config->isSupportPostHandshakeAuth is true or false. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_POSTHANDSHAKEAUTHSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_CFG_SetPostHandshakeAuthSupport(config, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetPostHandshakeAuthSupport(config, &isSupport) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetPostHandshakeAuthSupport(config, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_CFG_SetPostHandshakeAuthSupport(config, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_CFG_SetPostHandshakeAuthSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetPostHandshakeAuthSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_CFG_SetPostHandshakeAuthSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetPostHandshakeAuthSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_CIPHERSUITES_FUNC_TC001 * @title Test the HITLS_CFG_SetCipherSuites and HITLS_CFG_ClearTLS13CipherSuites interfaces. * @precon nan * @brief * 1. The client invokes the HITLS_CFG_SetCipherSuites interface to set the tls1.3 cipher suite HITLS_AES_128_GCM_SHA256. * Expected result 1. * 2. Call HITLS_CFG_ClearTLS13CipherSuites to clear the TLS1.3 algorithm suite. Expected result 2. * 3. Check whether the value of config->tls13CipherSuites is NULL and whether the value of config->tls13cipherSuitesSize * is 0. (Expected result 3) * 4. Establish a connection. Expected result 4. * @expect * 1. The setting is successful. * 2. The interface returns a success message. * 3. config->tls13CipherSuites, config->tls13cipherSuitesSize = 0 * 4. TLS1.3 initialization fails, and TLS1.2 connection are established. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_CIPHERSUITES_FUNC_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; uint16_t cipherSuites[1] = { HITLS_AES_128_GCM_SHA256 }; config_c = GetHitlsConfigViaVersion(tlsVersion); config_s = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(config_c, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_ClearTLS13CipherSuites(config_c) == HITLS_SUCCESS); ASSERT_TRUE(config_c->tls13CipherSuites == NULL); ASSERT_TRUE(config_c->tls13cipherSuitesSize == 0); FRAME_CertInfo certInfo = { "ecdsa/ca-nist521.der:ecdsa/inter-nist521.der:rsa_sha/ca-3072.der:rsa_sha/inter-3072.der", NULL, NULL, NULL, NULL, NULL,}; client = FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfo); if (tlsVersion == TLS1_3) { ASSERT_TRUE(client == NULL); goto EXIT; } ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @ * @test UT_TLS_CFG_SET_GET_KEYEXCHMODE_FUNC_TC001 * @title Setting the key exchange mode * @precon nan * @brief * 1. Call HITLS_CFG_SetKeyExchMode to set the key exchange mode to TLS13_KE_MODE_PSK_ONLY. Expected result 1 is * obtained. * 2. Invoke the HITLS_CFG_GetKeyExchMode interface. (Expected result 2) * 3. Call HITLS_CFG_SetKeyExchMode to set the key exchange mode to TLS13_KE_MODE_PSK_WITH_DHE. Expected result 3 is * obtained. * 4. Invoke the HITLS_CFG_GetKeyExchMode interface. (Expected result 4) * @expect * 1. The setting is successful. * 2. The returned value is the same as that of TLS13_KE_MODE_PSK_ONLY. * 3. The setting is successful. * 4. The return value of the interface is the same as that of TLS13_KE_MODE_PSK_WITH_DHE. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_KEYEXCHMODE_FUNC_TC001() { FRAME_Init(); ResumeTestInfo testInfo = {0}; testInfo.version = HITLS_VERSION_TLS13; testInfo.uioType = BSL_UIO_TCP; testInfo.config = HITLS_CFG_NewTLS13Config(); ASSERT_EQ(HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_ONLY), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_GetKeyExchMode(testInfo.config), TLS13_KE_MODE_PSK_ONLY); ASSERT_EQ(HITLS_CFG_SetKeyExchMode(testInfo.config, TLS13_KE_MODE_PSK_WITH_DHE), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_GetKeyExchMode(testInfo.config), TLS13_KE_MODE_PSK_WITH_DHE); EXIT: HITLS_CFG_FreeConfig(testInfo.config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_VERSIONSUPPORT_API_TC001 * @spec - * @title Test the HITLS_CFG_SetVersionSupport and HITLS_CFG_GetVersionSupport interfaces. * @precon nan * @brief HITLS_CFG_SetVersionSupport * 1. Import empty configuration information. Expected result 1. * 2. Transfer non-empty configuration information and set version to an invalid value. Expected result 2. * 3. Transfer non-empty configuration information and set version to a valid value. Expected result 3. * HITLS_CFG_GetVersionSupport * 1. Import empty configuration information. Expected result 1. * 2. Pass the null version pointer. Expected result 1. * 3. Transfer non-null configuration information and ensure that the version pointer is not null. Expected result 4 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned, and invalid values in config are filtered out. * 3. HITLS_SUCCES is returned and config is the expected value. * 4. The HITLS_SUCCES parameter is returned, and the version parameter is set to the value recorded in the config file. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_VERSIONSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; uint32_t version = 0; ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config, version) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetVersionSupport(config, &version) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetVersionSupport(config, NULL) == HITLS_NULL_INPUT); version = (TLS13_VERSION_BIT << 1) | TLS13_VERSION_BIT | TLS12_VERSION_BIT; ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); version = TLS13_VERSION_BIT | TLS12_VERSION_BIT; ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); uint32_t getversion = 0; ASSERT_TRUE(HITLS_CFG_GetVersionSupport(config, &getversion) == HITLS_SUCCESS); ASSERT_TRUE(getversion == config->version); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_ENCRYPTTHENMAC_API_TC001 * @spec - * @title Test the HITLS_CFG_SetEncryptThenMac and HITLS_CFG_GetEncryptThenMac interfaces. * @precon nan * @brief HITLS_CFG_SetEncryptThenMac * 1. Import empty configuration information. Expected result 1. * 2. Transfer non-null configuration information and set encryptThenMacType to an invalid value. Expected result 2 is * obtained. * 3. Transfer the non-empty configuration information and set encryptThenMacType to a valid value. Expected result 3 is * obtained. * HITLS_CFG_GetEncryptThenMac * 1. Import empty configuration information. Expected result 1. * 2. Pass the null encryptThenMacType pointer. Expected result 1. * 3. Transfer non-null configuration information and ensure that the encryptThenMacType pointer is not null. Expected * result 3. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and config->isEncryptThenMac is true. * 3. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_ENCRYPTTHENMAC_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; uint32_t encryptThenMacType = 0; ASSERT_TRUE(HITLS_CFG_SetEncryptThenMac(config, encryptThenMacType) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetEncryptThenMac(config, &encryptThenMacType) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetEncryptThenMac(config, NULL) == HITLS_NULL_INPUT); encryptThenMacType = 1; ASSERT_TRUE(HITLS_CFG_SetEncryptThenMac(config, encryptThenMacType) == HITLS_SUCCESS); encryptThenMacType = 2; ASSERT_TRUE(HITLS_CFG_SetEncryptThenMac(config, encryptThenMacType) == HITLS_SUCCESS); ASSERT_TRUE(config->isEncryptThenMac = true); uint32_t getencryptThenMacType = -1; ASSERT_TRUE(HITLS_CFG_GetEncryptThenMac(config, &getencryptThenMacType) == HITLS_SUCCESS); ASSERT_TRUE(getencryptThenMacType == config->isEncryptThenMac); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_IS_DTLS_API_TC001 * @title Test the HITLS_CFG_IsDtls interface. * @precon nan * @brief * 1. Transfer empty configuration information. Expected result 1. * 2. Transfer the null pointer isDtls. Expected result 1. * 3. Transfer the configuration information and ensure that the isDtls pointer is not null. Expected result 2 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. The HITLS_SUCCESS and isDtls information is returned. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_IS_DTLS_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; uint8_t isDtls = false; ASSERT_TRUE(HITLS_CFG_IsDtls(config, &isDtls) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_IsDtls(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_IsDtls(config, &isDtls) == HITLS_SUCCESS); ASSERT_TRUE(isDtls == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *s_config; HITLS_Config *c_config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; HITLS_TicketKeyCb serverKeyCb; } ResumeTestInfo1; HITLS_CRYPT_Key *cert_key = NULL; HITLS_CRYPT_Key* DH_CB(HITLS_Ctx *ctx, int32_t isExport, uint32_t keyLen) { (void)ctx; (void)isExport; (void)keyLen; return cert_key; } uint64_t RECORDPADDING_CB(HITLS_Ctx *ctx, int32_t type, uint64_t length, void *arg) { (void)ctx; (void)type; (void)length; (void)arg; return 100; } int32_t RecParseInnerPlaintext(TLS_Ctx *ctx, uint8_t *text, uint32_t *textLen, uint8_t *recType); int32_t STUB_RecParseInnerPlaintext(TLS_Ctx *ctx, uint8_t *text, uint32_t *textLen, uint8_t *recType) { (void)ctx; (void)text; (void)textLen; *recType = (uint8_t)REC_TYPE_APP; return HITLS_SUCCESS; } /** @ * @test UT_TLS_CFG_GET_RECORDPADDING_API_TC001 * @title HITLS_CFG_SetRecordPaddingCb Connection * @precon nan * @brief 1. If config is empty, expected result 1. 2. RecordPADDING_CB is empty. Expected result 2. 3. RecordPADDING_CB is not empty. Expected result 3. * @expect 1. The interface returns HITLS_NULL_INPUT. 2. The interface returns HITLS_SUCCESS. 3. The interface returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_RECORDPADDING_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); // Config is empty ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCb(NULL, RECORDPADDING_CB) == HITLS_NULL_INPUT); // RecordPADDING_CB is empty ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCb(config, NULL) == HITLS_SUCCESS); // RecordPADDING_CB is not empty ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCb(config, RECORDPADDING_CB) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetRecordPaddingCb(config) == RECORDPADDING_CB); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCbArg(config, RECORDPADDING_CB) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCbArg(NULL, RECORDPADDING_CB) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCbArg(config, NULL) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_RECORDPADDINGARG_API_TC001 * @title HITLS_CFG_SetRecordPaddingCbArg Connection * @precon nan * @brief 1. If config is empty, expected result 1. 2. RecordPADDING_CB is empty. Expected result 2. 3. RecordPADDING_CB is not empty. Expected result 3. * @expect 1. The interface returns HITLS_NULL_INPUT. 2. The interface returns HITLS_SUCCESS. 3. The interface returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_RECORDPADDINGARG_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); // Config is empty ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCb(NULL, RECORDPADDING_CB) == HITLS_NULL_INPUT); // RecordPADDING_CB is empty ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCb(config, NULL) == HITLS_SUCCESS); // RecordPADDING_CB is not empty ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCb(config, RECORDPADDING_CB) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetRecordPaddingCb(config) == RECORDPADDING_CB); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCbArg(config, RECORDPADDING_CB) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCbArg(NULL, RECORDPADDING_CB) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCbArg(config, NULL) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ int32_t EXAMPLE_TicketKeyCallback( uint8_t *keyName, uint32_t keyNameSize, HITLS_CipherParameters *cipher, uint8_t isEncrypt) { (void)keyName; (void)keyNameSize; (void)cipher; (void)isEncrypt; return 100; } /** @ * @test UT_TLS_CFG_SET_TICKET_CB_API_TC001 * @title Test HITLS_CFG_SetTicketKeyCallback interface * @brief 1. If config is empty, expected result 1. 2. HITLS_CFG_SetTicketKeyCallback is empty. Expected result 2 3. HITLS_CFG_SetTicketKeyCallback is not empty. Expected result 2 * @expect 1. Returns HITLS_NULL_INPUT. 2. Returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_TICKET_CB_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); // Config is empty ASSERT_TRUE(HITLS_CFG_SetTicketKeyCallback(NULL, EXAMPLE_TicketKeyCallback) == HITLS_NULL_INPUT); // HITLS_TicketKeyCb is empty ASSERT_TRUE(HITLS_CFG_SetTicketKeyCallback(config, NULL) == HITLS_SUCCESS); // HITLS_TicketKeyCb is not empty ASSERT_TRUE(HITLS_CFG_SetTicketKeyCallback(config, EXAMPLE_TicketKeyCallback) == HITLS_SUCCESS); SESSMGR_SetTicketKeyCb(config->sessMgr, EXAMPLE_TicketKeyCallback); ASSERT_EQ(SESSMGR_GetTicketKeyCb(config->sessMgr), EXAMPLE_TicketKeyCallback); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_NEW_DTLSCONFIG_API_TC001 * @title Test HITLS_CFG_NewDTLSConfig interface * @brief 1. Invoke the interface HITLS_CFG_NewTLS12Config, expected result 1. * @expect 1. Returns not NULL. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_NEW_DTLSCONFIG_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewDTLSConfig(); ASSERT_TRUE(config != NULL); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ #define DATA_MAX_LEN 1024 /** @ * @test UT_TLS_CFG_GET_SET_SESSION_TICKETKEY_API_TC001 * @title Test HITLS_CFG_SetSessionTicketKey interface * @brief 1. Register the memory for config structure. Expected result 1. * 2. If ticketKey is null, invoke HITLS_CFG_SetSessionTicketKey. Expected result 2. * 3. Invoke HITLS_CFG_SetSessionTicketKey. Expected result 3. * 4. If outSize is null, invoke HITLS_CFG_SetSessionTicketKey. Expected result 2. * 5. Invoke HITLS_CFG_SetSessionTicketKey. Expected result 3. * @expect 1. Memory register succeeded. * 2. Return HITLS_NULL_INPUT. * 3. Return HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_SET_SESSION_TICKETKEY_API_TC001(int version) { FRAME_Init(); HITLS_Config *config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); uint8_t getKey[DATA_MAX_LEN] = {0}; uint32_t getKeySize = DATA_MAX_LEN; uint32_t outSize = 0; char *ticketKey = "748ab9f3dc1a23748ab9f3dc1a23748ab9f3dc1a23748ab9f3dc1a23748ab9f3dc1a23748ab9f3d"; uint32_t ticketKeyLen = HITLS_TICKET_KEY_NAME_SIZE + HITLS_TICKET_KEY_SIZE + HITLS_TICKET_KEY_SIZE; ASSERT_TRUE(HITLS_CFG_SetSessionTicketKey(config, NULL, ticketKeyLen) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetSessionTicketKey(config, (uint8_t *)ticketKey, ticketKeyLen) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetSessionTicketKey(config, getKey, getKeySize, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetSessionTicketKey(config, getKey, getKeySize, &outSize) == HITLS_SUCCESS); ASSERT_TRUE(outSize == ticketKeyLen); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CFG_ADD_CAINDICATION_API_TC001 * @title: Test Add different CA flag indication types. * @brief * 1. If data is NULL, Invoke the HITLS_CFG_AddCAIndication.Expected result 1. * 2. Invoke the HITLS_CFG_AddCAIndication and set the transferred caType to HITLS_TRUSTED_CA_PRE_AGREED.Expected * result 2. * 3. Invoke the HITLS_CFG_AddCAIndication and set the transferred caType to HITLS_TRUSTED_CA_KEY_SHA1.Expected * result 2. * 4. Invoke the HITLS_CFG_AddCAIndication and set the transferred caType to HITLS_TRUSTED_CA_X509_NAME.Expected * result 2. * 5. Invoke the HITLS_CFG_AddCAIndication and set the transferred caType to HITLS_TRUSTED_CA_CERT_SHA1.Expected * result 2. * 6. Invoke the HITLS_CFG_AddCAIndication and set the transferred caType to HITLS_TRUSTED_CA_UNKNOWN.Expected * result 2. * @expect * 1. Return HITLS_NULL_INPUT. * 2. Return HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_ADD_CAINDICATION_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; uint8_t data[] = {0}; uint32_t len = sizeof(data); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_PRE_AGREED, NULL, len) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_PRE_AGREED, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_KEY_SHA1, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_X509_NAME, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_CERT_SHA1, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_UNKNOWN, data, len) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_CALIST_API_TC001 * @title Test HITLS_CFG_GetCAList interface * @brief * 1.Register the memory for config structure. Expected result 1. * 1.Invoke the interface HITLS_CFG_GetCAList, expected result 2. * @expect 1. Returns not NULL. * 2. Returns NULL. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_CALIST_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); ASSERT_TRUE(HITLS_CFG_GetCAList(config) == NULL); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_GET_VERSION_API_TC001 * @title Test HITLS_CFG_GetMinVersion/HITLS_CFG_GetMaxVersion/HITLS_SetVersion interface * @brief * 1.If minVersion is NULL, Invoke the HITLS_CFG_GetMinVersion.Expected result 1. * 2.If maxVersion is NULL, Invoke the HITLS_CFG_GetMinVersion.Expected result 1. * 3.Invoke HITLS_CFG_SetVersion.Expected result 2. * 4.Invoke HITLS_CFG_GetMinVersion.Expected result 2. * 5.Invoke HITLS_CFG_GetMaxVersion.Expected result 2. * 6. Check minVersion is HITLS_VERSION_TLS12 and maxVersion is HITLS_VERSION_TLS13 * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCES * 3. Return HITLS_SUCCES,minVersion is HITLS_VERSION_TLS12 and maxVersion is HITLS_VERSION_TLS13 @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_VERSION_API_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLSConfig(); uint16_t minVersion = 0; uint16_t maxVersion = 0; ASSERT_TRUE(HITLS_CFG_GetMinVersion(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetVersion(config, HITLS_VERSION_TLS12, HITLS_VERSION_TLS13) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMinVersion(config, &minVersion) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(config, &maxVersion) == HITLS_SUCCESS); ASSERT_TRUE(minVersion == HITLS_VERSION_TLS12 && maxVersion == HITLS_VERSION_TLS13); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_SESSION_CACHEMODE_API_TC001 * @title Test ITLS_CFG_GetSessionCacheMoe interface * @brief 1. Register the memory for config structure. Expected result 1. * 2. Invoke HITLS_CFG_GetSessionCacheMode. Expected result 2. * @expect 1. Memory register succeeded. * 2. Return success and value is 0. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_SESSION_CACHEMODE_API_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_SESS_CACHE_MODE getCacheMode = 0; ASSERT_EQ(HITLS_CFG_GetSessionCacheMode(config, &getCacheMode), 0); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SET_GET_SESSIONCACHESIZE_API_TC001 * @title Test HITLS_CFG_SetSessionCacheSize/HITLS_CFG_GetSessionCacheSize interface * @brief 1. Register the memory for config structure. Expected result 1. * 2. Invoke HITLS_CFG_SetSessionCacheSize. Expected result 2. * 3. Invoke HITLS_CFG_GetSessionCacheSize. Expected result 2. * 4. Check getCacheSize and cacheSize is equal * @expect 1. Memory register succeeded. * 2. Return HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_SESSIONCACHESIZE_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); uint32_t cacheSize = 10; uint32_t getCacheSize = 0; ASSERT_TRUE(HITLS_CFG_SetSessionCacheSize(config, cacheSize) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetSessionCacheSize(config, &getCacheSize) == HITLS_SUCCESS); ASSERT_TRUE(getCacheSize == cacheSize); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SET_GET_SESSION_TIMEOUT_API_TC001 * @title Test HITLS_CFG_GetSessionTimeout interface * @brief 1. Register the memory for config structure. Expected result 1. * 2. Invoke HITLS_CFG_SetSessionTimeout. Expected result 2. * 3. Invoke HITLS_CFG_GetSessionTimeout. Expected result 2. * 4. Check timeOut and getTimeOut is equal * @expect 1. Memory register succeeded. * 2. Return HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_SESSION_TIMEOUT_API_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); uint64_t timeOut = 10; uint64_t getTimeOut = 0; ASSERT_TRUE(HITLS_CFG_SetSessionTimeout(config, timeOut) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetSessionTimeout(config, &getTimeOut) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_VERSIONFORBID_API_TC001 * @title Test HITLS_SetVersionForbid interface * @brief 1. Register the memory for config structure. Expected result 1. * 2. If context is NULL, invoke HITLS_SetVersionForbid. Expected result 3. * 3. If context is NULL, invoke HITLS_SetVersionForbid. Expected result 2. * @expect 1. Memory register succeeded. * 2. Return HITLS_SUCCESS. * 3. Return HITLS_NULL_INPUT @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_VERSIONFORBID_API_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetVersionForbid(NULL, HITLS_VERSION_TLS12) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetVersionForbid(ctx, HITLS_VERSION_TLS12) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_CONFIGUSEDATA_API_TC001 * @title Test HITLS_CFG_SetConfigUserData/HITLS_CFG_GetConfigUserData interfaces * @brief 1. Register the memory for config structure. Expected result 1. * 2. If config is NULL, invoke HITLS_CFG_SetConfigUserData. Expected result 2. * 3. Invoke HITLS_CFG_SetConfigUserData. Expected result 3. * 3. Invoke HITLS_CFG_SetConfigUserData. Expected result 4. * @expect 1. Memory register succeeded. * 2. Return HITLS_NULL_INPUT. * 3. Return HITLS_SUCCESS. * 4. Return not NULL. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_CONFIGUSEDATA_API_TC001(int version) { FRAME_Init(); HITLS_Config *config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); char *userData = "123456"; ASSERT_TRUE(HITLS_CFG_SetConfigUserData(NULL, userData) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetConfigUserData(config, userData) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetConfigUserData(config) != NULL); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ void EXAMPLE_HITLS_ConfigUserDataFreeCb( void* data) { (void)data; return; } /** @ * @test UT_TLS_CFG_SET_CONFIG_USERDATA_FREECB_API_TC001 * @title Test HITLS_CFG_SetConfigUserDataFreeCb interfaces * @brief 1. Register the memory for config structure. Expected result 1. * 2. If config is NULL, invoke HITLS_CFG_SetConfigUserDataFreeCb. Expected result 2. * 3. Invoke HITLS_CFG_SetConfigUserDataFreeCb. Expected result 3. * @expect 1. Memory register succeeded. * 2. Return HITLS_NULL_INPUT. * 3. Return HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_CONFIG_USERDATA_FREECB_API_TC001(int version) { FRAME_Init(); HITLS_Config *config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); ASSERT_TRUE(HITLS_CFG_SetConfigUserDataFreeCb(NULL, EXAMPLE_HITLS_ConfigUserDataFreeCb) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetConfigUserDataFreeCb(config, EXAMPLE_HITLS_ConfigUserDataFreeCb) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_CERTIFICATE_API_TC001 * @title Test HITLS_CFG_SetCertificate interface * @brief 1. Invoke the HITLS_CFG_SetCertificate interface, set tlsConfig to null, and set cert for the device * certificate. (Expected result 1) * 2. Invoke the HITLS_CFG_SetCertificate interface. Set tlsConfig and cert to an empty value for the device * certificate.(Expected result 1) * 3. Invoke the HITLS_CFG_SetCertificate interface. Ensure that tlsConfig and cert are not empty. Perform deep * copy. (Expected result 3) * 4. Invoke the HITLS_CFG_GetCertificate interface. The value of tlsConfig->certMgrCtx->currentCertKeyType is * greater than the value of TLS_CERT_KEY_TYPE_UNKNOWN, Expected result 4 is obtained. * 5. Invoke the HITLS_CFG_GetCertificate interface and leave tlsConfig empty. Expected result 4 is obtained. * 6. Invoke the HITLS_CFG_SetCertificate interface, set tlsConfig->certMgrCtx to null, and set cert to a non-empty * device certificate. (Expected result 2) * 7. Invoke HITLS_CFG_GetCertificate * Run the tlsConfig command to set certMgrCtx to null. Expected result 4 is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Return HITLS_CERT_ERR_X509_DUP * 3. HITLS_SUCCESS is returned. * 4. NULL is returned. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_CERTIFICATE_API_TC001(int version, char *certFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_CERT_X509 *cert = HiTLS_X509_LoadCertFile(tlsConfig, certFile); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_SetCertificate(NULL, cert, false) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetCertificate(tlsConfig, NULL, true) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_CFG_SetCertificate(tlsConfig, cert, true), HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetCertificate(tlsConfig) != NULL); tlsConfig->certMgrCtx->currentCertKeyType = TLS_CERT_KEY_TYPE_UNKNOWN; ASSERT_TRUE(HITLS_CFG_GetCertificate(tlsConfig) == NULL); ASSERT_TRUE(HITLS_CFG_GetCertificate(NULL) == NULL); SAL_CERT_MgrCtxFree(tlsConfig->certMgrCtx); tlsConfig->certMgrCtx = NULL; ASSERT_EQ(HITLS_CFG_SetCertificate(tlsConfig, cert, true), HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetCertificate(tlsConfig) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); SAL_CERT_X509Free(cert); } /* END_CASE */ /* @ * @test UT_TLS_CFG_CHECK_PRIVATEKEY_API_TC001 * @title Test HITLS_CFG_CheckPrivateKey interface * @brief 1. Invoke the HITLS_CFG_CheckPrivateKey interface and leave tlsConfig blank. Expected result 1 * 2. Invoke the HITLS_CFG_CheckPrivateKey interface. The tlsConfig parameter is not empty, * The value of tlsConfig->certMgrCtx->currentCertKeyType is greater than or equal to the maximum value * TLS_CERT_KEY_TYPE_UNKNOWN. Expected result 2 * 3. Invoke the HITLS_CFG_CheckPrivateKey interface and leave tlsConfig->certMgrCtx empty. Expected result 3 * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_CONFIG_NO_CERT is returned. * 3. The HITLS_UNREGISTERED_CALLBACK message is returned. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_CHECK_PRIVATEKEY_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_CheckPrivateKey(NULL) == HITLS_NULL_INPUT); tlsConfig->certMgrCtx->currentCertKeyType = TLS_CERT_KEY_TYPE_UNKNOWN; ASSERT_TRUE(HITLS_CFG_CheckPrivateKey(tlsConfig) == HITLS_CONFIG_NO_CERT); SAL_CERT_MgrCtxFree(tlsConfig->certMgrCtx); tlsConfig->certMgrCtx = NULL; ASSERT_TRUE(HITLS_CFG_CheckPrivateKey(tlsConfig) == HITLS_UNREGISTERED_CALLBACK); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /** @ * @test UT_TLS_CFG_ADD_CHAINCERT_API_TC001 * @title Test HITLS_CFG_GetChainCerts interface * @brief 1. Invoke the HITLS_CFG_AddChainCert interface, set tlsConfig to null, and set addCert to a certificate to be * added. Perform shallow copy. Expected result 1 . * 2. Invoke the HITLS_CFG_AddChainCert interface. The tlsConfig parameter is not empty and the addCert parameter * is empty.Perform deep copy. Expected result 1 . * 3. Invoke the HITLS_CFG_AddChainCert interface. Ensure that tlsConfig is not empty and addCert is not empty. * Perform shallow copy. Expected result 2 . * 4. Invoke the HITLS_CFG_AddChainCert interface. The value of tlsConfig is not empty and the value of * tlsConfig->certMgrCtx->currentCertKeyType is greater than or equal to the maximum value TLS_CERT_KEY_TYPE_UNKNOWN. * Expected result 4 . * 5. Invoke the HITLS_CFG_GetChainCerts interface. Set tlsConfig to a value greater than or equal to the maximum * value TLS_CERT_KEY_TYPE_UNKNOWN. (Expected result 3) * 6. Invoke the HITLS_CFG_GetChainCerts interface and leave tlsConfig blank. Expected result 3 . * 7. Invoke the HITLS_CFG_LoadKeyBuffer interface. Set tlsConfig->certMgrCtx to null and addCert to the * certificate to be added. Perform deep copy. Expected result 5 . * 8. Invoke the HITLS_CFG_GetChainCerts interface and leave tlsConfig->certMgrCtx empty. Expected result 3. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCESS is returned. * 3. NULL is returned. * 4. Return ITLS_CERT_ERR_ADD_CHAIN_CERT * 5. Return HITLS_CERT_ERR_X509_DUP @ */ /* BEGIN_CASE */ void UT_TLS_CFG_ADD_CHAINCERT_API_TC001(int version, char *certFile, char *addCertFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_CERT_X509 *cert = HITLS_CFG_ParseCert(tlsConfig, (const uint8_t *)certFile, strlen(certFile) + 1, TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); cert = HiTLS_X509_LoadCertFile(tlsConfig, certFile); HITLS_CERT_X509 *addCert = HiTLS_X509_LoadCertFile(tlsConfig, addCertFile); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_SetCertificate(tlsConfig, cert, false) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddChainCert(NULL, addCert, false) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_AddChainCert(tlsConfig, NULL, true) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_CFG_AddChainCert(tlsConfig, addCert, false), HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetChainCerts(tlsConfig) != NULL); tlsConfig->certMgrCtx->currentCertKeyType = TLS_CERT_KEY_TYPE_UNKNOWN; ASSERT_EQ(HITLS_CFG_AddChainCert(tlsConfig, cert, true), HITLS_CERT_ERR_ADD_CHAIN_CERT); ASSERT_TRUE(HITLS_CFG_GetChainCerts(tlsConfig) == NULL); ASSERT_TRUE(HITLS_CFG_GetChainCerts(NULL) == NULL); SAL_CERT_MgrCtxFree(tlsConfig->certMgrCtx); tlsConfig->certMgrCtx = NULL; ASSERT_EQ(HITLS_CFG_AddChainCert(tlsConfig, cert, true), HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetChainCerts(tlsConfig) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /** @ * @test UT_HITLS_CFG_REMOVE_CERTANDKEY_API_TC001 * @title Test HITLS_CFG_RemoveCertAndKey interface * @brief * 1. Register the memory for config structure. Expected result 1. * 2. Invoke HITLS_CFG_RemoveCertAndKey interface, expected result 3. * 3. Invoke HITLS_CFG_SetCertificate interface, expected result 3. * 4. Invoke HITLS_CFG_LoadKeyFile interface, expected result 3. * 5. Invoke HITLS_CFG_GetCertificate interface, expected result 2. * 6. Invoke HITLS_CFG_GetPrivateKey interface, expected result 2. * 7. Invoke HITLS_CFG_CheckPrivateKey interface, expected result 3. * 8. Invoke HITLS_CFG_RemoveCertAndKey interface, expected result 3. * 9. Invoke HITLS_CFG_GetCertificate interface, expected result 4. * 10. Invoke HITLS_CFG_GetPrivateKey interface, expected result 4. * @expect 1. Create successful. * 2. Return not NULL * 3. Return HITLS_SUCCESS * 4.Return NULL @ */ /* BEGIN_CASE */ void UT_HITLS_CFG_REMOVE_CERTANDKEY_API_TC001(int version, char *certFile, char *keyFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_CERT_X509 *cert = HiTLS_X509_LoadCertFile(tlsConfig, certFile); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_EQ(HITLS_CFG_RemoveCertAndKey(tlsConfig), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetCertificate(tlsConfig, cert, true), HITLS_SUCCESS); #ifdef HITLS_TLS_FEATURE_PROVIDER ASSERT_EQ(HITLS_CFG_ProviderLoadKeyFile(tlsConfig, keyFile, "ASN1", NULL), HITLS_SUCCESS); #else ASSERT_EQ(HITLS_CFG_LoadKeyFile(tlsConfig, keyFile, TLS_PARSE_FORMAT_ASN1), HITLS_SUCCESS); #endif ASSERT_TRUE(HITLS_CFG_GetCertificate(tlsConfig) != NULL); ASSERT_TRUE(HITLS_CFG_GetPrivateKey(tlsConfig) != NULL); ASSERT_EQ(HITLS_CFG_CheckPrivateKey(tlsConfig), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_RemoveCertAndKey(tlsConfig), HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetCertificate(tlsConfig) == NULL); ASSERT_TRUE(HITLS_CFG_GetPrivateKey(tlsConfig) == NULL); EXIT: HITLS_CFG_FreeCert(tlsConfig, cert); HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ void StubListDataDestroy(void *data) { BSL_SAL_FREE(data); return; } /** @ * @test UT_HITLS_CFG_ADD_EXTRA_CHAINCERT_API_TC001 * @title Test HITLS_CFG_AddExtraChainCert interface * @brief * 1. Create a config object. Expected result 1 . * 2. If the input value of config is null, invoke HITLS_CFG_GetExtraChainCerts to obtain the configured additional * certificate chain. Expected result 2 . * 3. Call the interface to add a certificate to the additional certificate chain and call HITLS_CFG_GetExtraChainCerts * to obtain the configured additional certificate chain. Expected result 3 . * 4. Call the API again to add certificate 2 to the additional certificate chain and call HITLS_CFG_GetExtraChainCerts * to obtain the configured additional certificate chain. Expected result 4 . 5. Invoke HITLS_CFG_ClearChainCerts to clear the attached certificate chain. Expected result 5 . * @expect * 1. The config object is created successfully. * 2. Failed to set the additional certificate chain. The obtained additional certificate chain is empty. * 3. The additional certificate chain is successfully set and obtained. * 4. The additional certificate chain is successfully set and obtained. * 5. The STORE for obtaining the attached certificate chain does not change. @ */ /* BEGIN_CASE */ void UT_HITLS_CFG_ADD_EXTRA_CHAINCERT_API_TC001(int version, char *certFile1, char *certFile2) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_CERT_X509 *cert1 = HiTLS_X509_LoadCertFile(tlsConfig, certFile1); HITLS_CERT_X509 *cert2 = HiTLS_X509_LoadCertFile(tlsConfig, certFile2); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_AddExtraChainCert(NULL, cert1) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_AddExtraChainCert(tlsConfig, cert1) == HITLS_SUCCESS); HITLS_CERT_Chain *extraChainCert = HITLS_CFG_GetExtraChainCerts(tlsConfig); ASSERT_TRUE(extraChainCert->count == 1); ASSERT_TRUE(HITLS_CFG_GetExtraChainCerts(tlsConfig) != NULL); ASSERT_TRUE(HITLS_CFG_AddExtraChainCert(tlsConfig, cert2) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetExtraChainCerts(tlsConfig) != NULL); ASSERT_TRUE(HITLS_CFG_ClearChainCerts(tlsConfig) == HITLS_SUCCESS); HITLS_CERT_Chain *extraChainCert1 = HITLS_CFG_GetExtraChainCerts(tlsConfig); ASSERT_TRUE(extraChainCert1->count == 2); ASSERT_TRUE(HITLS_CFG_GetExtraChainCerts(tlsConfig) != NULL); ASSERT_TRUE(HITLS_CFG_ClearExtraChainCerts(NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_ClearExtraChainCerts(tlsConfig) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetExtraChainCerts(tlsConfig) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SET_DTLS_MTU_API_TC001 * @title Test HITLS_SetMtu interface * @brief 1. Create the TLS configuration object config.Expect result 1. * 2. Use config to create the client and server.Expect result 2. * 3. Invoke HITLS_SetMtu, Expect result 3. * @expect 1. The config object is successfully created. * 2. The client and server are successfully created. * 3. Return HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_DTLS_MTU_API_TC001(void) { FRAME_Init(); uint32_t mtu = 1500; HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(HITLS_SetMtu(client->ssl, mtu) == HITLS_SUCCESS); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_SetMtu(server->ssl, mtu) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ void Test_HITLS_KeyLogCb(HITLS_Ctx *ctx, const char *line) { (void)ctx; (void)line; printf("there is Test_HITLS_KeyLogCb\n"); } /* @ * @test UT_TLS_CFG_LogSecret_TC001 * @spec - * @title Test the HITLS_LogSecret interface. * @precon nan * @brief * 1. Transfer an empty context. The label and secret are not empty, and the secret length is not 0. * Expected result 1 is obtained. * 2. Transfer a non-empty context. The label is empty, the secret is not empty, * and the secret length is not 0. Expected result 1 is obtained. * 3. Transfer a non-empty context. The label is not empty, the secret is empty, * and the secret length is not 0. Expected result 1 is obtained. * 4. Transfer a non-empty context. The label and secret are not empty, and the secret length is 0. * Expected result 1 is obtained. * 5. Transfer a non-empty context. The label and secret are not empty, and the secret length is not 0. * Expected result 2 is obtained. * @expect 1. return HITLS_NULL_INPUT * 2. return HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_LogSecret_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = NULL; HITLS_CFG_SetKeyLogCb(config, Test_HITLS_KeyLogCb); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); const char label[] = "hello"; const char secret[] = "hello123"; ASSERT_EQ(HITLS_LogSecret(NULL, label, (const uint8_t *)secret, strlen(secret)), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_LogSecret(ctx, NULL, (const uint8_t *)secret, strlen(secret)), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_LogSecret(ctx, label, NULL, strlen(secret)), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_LogSecret(ctx, label, (const uint8_t *)secret, 0), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_LogSecret(ctx, label, (const uint8_t *)secret, strlen(secret)), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SetTmpDhCb_TC001 * @spec - * @title HITLS_CFG_SetTmpDhCb interface test. The config field is empty. * @precon nan * @brief 1. If config is empty, expected result 1 is obtained. * @expect 1. HITLS_NULL_INPUT is returned. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SetTmpDhCb_TC001() { // config is empty ASSERT_TRUE(HITLS_CFG_SetTmpDhCb(NULL, DH_CB) == HITLS_NULL_INPUT); EXIT: ; } /* END_CASE */ /* @ * @test UT_TLS_CFG_GET_CIPHERSUITESBYSTDNAME_TC001 * @spec - * @title HITLS_CFG_GetCipherSuiteByStdName connection * @precon nan * @brief 1. Transfer a null pointer. Expected result 1 is obtained. * 2. Transfer the "TLS_RSA_WITH_AES_128_CBC_SHA" character string. Expected result 2 is obtained. * 3. Input the character string x. Expected result 3 is obtained. * @expect 1. return NULL * 2. return HITLS_RSA_WITH_AES_128_CBC_SHA * 3. return NULL @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_CIPHERSUITESBYSTDNAME_TC001(void) { const char *StdName = NULL; ASSERT_TRUE(HITLS_CFG_GetCipherSuiteByStdName((const uint8_t *)StdName) == NULL); const char StdName2[] = "TLS_RSA_WITH_AES_128_CBC_SHA"; const HITLS_Cipher* Cipher2 = HITLS_CFG_GetCipherSuiteByStdName((const uint8_t *)StdName2); ASSERT_TRUE(Cipher2->cipherSuite == HITLS_RSA_WITH_AES_128_CBC_SHA); const char StdName3[] = "x"; ASSERT_TRUE(HITLS_CFG_GetCipherSuiteByStdName((const uint8_t *)StdName3) == NULL); EXIT: return; } /* END_CASE */ /* @ * @test UT_TLS_CFG_CLEAR_CALIST_TC001 * @title HITLS_CFG_ClearCAList interface test * @precon nan * @brief 1. pass NULL parameter, expect result 1 * 2. pass config with NULL caList, expect result 1 * 3. pass normal config, expect result 1 * @expect 1. void function has no return value * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_CFG_CLEAR_CALIST_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Config *config2 = {0}; HITLS_CFG_ClearCAList(NULL); HITLS_CFG_ClearCAList(config2); HITLS_CFG_ClearCAList(config); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SET_GET_DHAUTOSUPPORT_TC001 * @spec - * @title HITLS_CFG_SetDhAutoSupport and HITLS_CFG_GetDhAutoSupport contact * @precon nan * @brief HITLS_CFG_SetDhAutoSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set support to an invalid value. Expected result 2 is obtained. * 3. Transfer non-empty configuration information and set support to a valid value. Expected result 3 is obtained. * HITLS_CFG_GetDhAutoSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer an empty isSupport pointer. Expected result 1 is obtained. * 3. Transfer the non-null configuration information and the isSupport pointer is not null. Expected result 3 is obtained. * @expect 1. return HITLS_NULL_INPUT * 2. return HITLS_SUCCES,and config->isSupportDhAuto is True * 3. return HITLS_SUCCES,and config->isSupportDhAuto is False or True @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_DHAUTOSUPPORT_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_CFG_SetDhAutoSupport(config, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetDhAutoSupport(config, &isSupport) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetDhAutoSupport(config, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_CFG_SetDhAutoSupport(config, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_CFG_SetDhAutoSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetDhAutoSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_CFG_SetDhAutoSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetDhAutoSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_GET_READ_AHEAD_TC001 * @title HITLS_CFG_GetReadAhead interface test * @precon nan * @brief 1. pass NULL config, expect result 1 * 2. pass NULL onOff, expect result 1 * 3. pass normal parameters, expect result 2 * @expect 1. return HITLS_NULL_INPUT * 2. return HITLS_SUCCESS * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_READ_AHEAD_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); int32_t onOff = 0; ASSERT_TRUE(HITLS_CFG_GetReadAhead(NULL, &onOff) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetReadAhead(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetReadAhead(config, &onOff) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_CONFIG_SET_KeyLogCb_TC001 * @spec - * @title Test the HITLS_CFG_SetKeyLogCb and HITLS_CFG_GetKeyLogCb interfaces. * @precon nan * @brief HITLS_CFG_SetKeyLogCb and HITLS_CFG_GetKeyLogCb * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set callback to a non-empty value. Expected result 2 is obtained. * @expect 1. return HITLS_NULL_INPUT * 2. return HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_KeyLogCb_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); ASSERT_TRUE(HITLS_CFG_SetKeyLogCb(NULL, Test_HITLS_KeyLogCb) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetKeyLogCb(config, Test_HITLS_KeyLogCb) == HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_GetKeyLogCb(NULL), NULL); ASSERT_EQ(HITLS_CFG_GetKeyLogCb(config), Test_HITLS_KeyLogCb); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ int g_recordPaddingCbArg = 1; uint64_t RecordPaddingCb(HITLS_Ctx *ctx, int32_t type, uint64_t length, void *arg) { (void)ctx; (void)type; (void)length; ASSERT_TRUE(g_recordPaddingCbArg == (*(int *)arg)); ASSERT_TRUE(&g_recordPaddingCbArg == arg); EXIT: return 0; } /** @ * @test UT_TLS_CFG_SET_RECORDPADDINGARG_API_TC002 * @title HITLS_CFG_SetRecordPaddingCbArg Connection * @precon nan * @brief 1. Create tls13 config, expected result 1. 2. Set RecordPaddingCb and RecordPaddingCbArg to 1 for the client, Expected result 2. 3. Establish a connection, Verify that the arg passed in RecordPaddingCb matches the set arg. Expected result 3. * @expect * 1. The creating is successful. * 2. The setting is successful. * 3. The arg value is the same,TLS1.3 connection are established. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_RECORDPADDINGARG_API_TC002() { HitlsInit(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config_c = HITLS_CFG_NewTLS13Config(); config_s = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCb(config_c, RecordPaddingCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetRecordPaddingCbArg(config_c, &g_recordPaddingCbArg) == HITLS_SUCCESS); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CFG_LOADVERIFYDIR_MULTI_PATH_TC001 * @title Test HITLS_CFG_LoadVerifyDir with multiple CA paths * @brief * 1. Create a config object. * 2. Pass in a string containing multiple paths (such as "/tmp/ca1:/tmp/ca2:/tmp/ca3"). * 3. Call HITLS_CFG_LoadVerifyDir. * 4. Check that the number and content of caPaths in the cert store are consistent with the input. * @expect * 1. The interface returns success. * 2. The number and content of paths in the cert store are consistent with the input. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_LOADVERIFYDIR_MULTI_PATH_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); const char *multi_path = "/tmp/ca1:/tmp/ca2:/tmp/ca3:/tmp/ca3"; int32_t ret = HITLS_CFG_LoadVerifyDir(config, multi_path); ASSERT_TRUE(ret == HITLS_SUCCESS); HITLS_CERT_Store *store = SAL_CERT_GetCertStore(config->certMgrCtx); ASSERT_TRUE(store != NULL); HITLS_X509_StoreCtx *storeCtx = (HITLS_X509_StoreCtx *)store; BslList *caPaths = storeCtx->caPaths; ASSERT_TRUE(caPaths != NULL); int expect_count = 3; int actual_count = BSL_LIST_COUNT(caPaths); ASSERT_TRUE(actual_count == expect_count); const char *expect_paths[] = {"/tmp/ca1", "/tmp/ca2", "/tmp/ca3"}; for (int i = 0; i < expect_count; ++i) { const char *path = (const char *)BSL_LIST_GetIndexNode(i, caPaths); ASSERT_TRUE(path != NULL); ASSERT_TRUE(strcmp(path, expect_paths[i]) == 0); } EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_LOADVERIFYFILE_TC001 * @title Test HITLS_CFG_LoadVerifyFile with a single CA path * @brief * 1. Create a config object. * 2. Pass in a string containing a single path. * 3. Call HITLS_CFG_LoadVerifyFile. * 4. Load a client certificate signed by the CA in the specified path. * 5. Call HITLS_CFG_BuildCertChain to verify the client certificate. * @expect * 1. The interface returns success. * 2. The client certificate is successfully verified. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_LOADVERIFYFILE_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); const char *path = "../testdata/tls/certificate/pem/rsa_sha256/inter.pem"; int32_t ret = HITLS_CFG_LoadVerifyFile(config, path); ASSERT_EQ(ret, HITLS_SUCCESS); const char *path1 = "../testdata/tls/certificate/pem/rsa_sha256/ca.pem"; ret = HITLS_CFG_LoadVerifyFile(config, path1); ASSERT_EQ(ret, HITLS_SUCCESS); const char *certToVerify = "../testdata/tls/certificate/pem/rsa_sha256/client.pem"; ret = HITLS_CFG_LoadCertFile(config, certToVerify, TLS_PARSE_FORMAT_PEM); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_BuildCertChain(config, HITLS_BUILD_CHAIN_FLAG_NO_ROOT), HITLS_SUCCESS); HITLS_CERT_Chain *chain = HITLS_CFG_GetChainCerts(config); ASSERT_TRUE(chain != NULL); ASSERT_TRUE(chain->count == 1); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_LOADVERIFYFILE_TC002 * @title Test HITLS_CFG_LoadVerifyFile with a single CA path * @brief * 1. Create a config object. * 2. Pass in a string containing a single path. * 3. Call HITLS_CFG_LoadVerifyFile. * 4. Load a client certificate signed by the CA in the specified path. * 5. Call HITLS_CFG_BuildCertChain to verify the client certificate. * @expect * 1. The interface returns success. * 2. The client certificate verification fails. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_LOADVERIFYFILE_TC002(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); const char *path = "../testdata/tls/certificate/pem/ecdsa_sha256/inter.pem"; int32_t ret = HITLS_CFG_LoadVerifyFile(config, path); ASSERT_EQ(ret, HITLS_SUCCESS); const char *certToVerify = "../testdata/tls/certificate/pem/rsa_sha256/client.pem"; ret = HITLS_CFG_LoadCertFile(config, certToVerify, TLS_PARSE_FORMAT_PEM); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_BuildCertChain(config, HITLS_BUILD_CHAIN_FLAG_NO_ROOT), HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetChainCerts(config) == NULL); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_USECERTCHAINFILE_TC001 * @title Test HITLS_CFG_UseCertificateChainFile with a single file path * @brief * 1. Create a config object. * 2. Pass in a string containing a single path. * 3. Call HITLS_CFG_UseCertificateChainFile. * 4. Load a client certificate signed by the CA in the specified path. * 5. Call HITLS_CFG_BuildCertChain to verify the client certificate. * @expect * 1. The interface returns success. * 2. The client certificate verification verified. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_USECERTCHAINFILE_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); const char *path = "../testdata/tls/certificate/pem/rsa_sha256/cert_chain.pem"; int32_t ret = HITLS_CFG_UseCertificateChainFile(config, path); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_BuildCertChain(config, HITLS_BUILD_CHAIN_FLAG_CHECK), HITLS_SUCCESS); HITLS_CERT_Chain *chain = HITLS_CFG_GetChainCerts(config); ASSERT_TRUE(chain != NULL); ASSERT_TRUE(chain->count == 1); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_USECERTCHAINFILE_TC002 * @title Test HITLS_CFG_UseCertificateChainFile with a single CA path * @brief * 1. Create a config object. * 2. Pass in a string containing a single path. * 3. Call HITLS_CFG_UseCertificateChainFile. * 4. Load a client certificate signed by the CA in the specified path. * 5. Call HITLS_CFG_BuildCertChain to verify the client certificate. * @expect * 1. The interface returns success. * 2. The client certificate verification fails. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_USECERTCHAINFILE_TC002(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); const char *path = "../testdata/tls/certificate/pem/rsa_sha256/cert_chain_damaged_ca.pem"; int32_t ret = HITLS_CFG_UseCertificateChainFile(config, path); ASSERT_EQ(ret, HITLS_CFG_ERR_LOAD_CERT_FILE); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_USECERTCHAINFILE_TC003 * @title Test HITLS_CFG_LoadVerifyFile with a single CA path * @brief * 1. Create a config object. * 2. Pass in a string containing a single path. * 3. Call HITLS_CFG_UseCertificateChainFile. * 4. Load a client certificate signed by the CA in the specified path. * 5. Call HITLS_CFG_BuildCertChain to verify the client certificate. * @expect * 1. The interface returns success. * 2. The client certificate verification fails. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_USECERTCHAINFILE_TC003(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); const char *path = "../testdata/tls/certificate/pem/rsa_sha256/cert_chain_duplicate_ca.pem"; int32_t ret = HITLS_CFG_UseCertificateChainFile(config, path); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_BuildCertChain(config, HITLS_BUILD_CHAIN_FLAG_CHECK), HITLS_CERT_STORE_CTRL_ERR_ADD_CERT_LIST); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface/test_suite_sdv_frame_tls_config_1.c
C
unknown
73,676
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "securec.h" #include "hlt.h" #include "hitls_error.h" #include "hitls_func.h" #include "conn_init.h" #include "frame_tls.h" #include "frame_link.h" #include "alert.h" #include "stub_replace.h" #include "hs_common.h" #include "change_cipher_spec.h" #include "hs.h" #include "simulate_io.h" #include "rec_header.h" #include "rec_wrapper.h" #include "recv_client_hello.c" #include "record.h" #define READ_BUF_SIZE 18432 #define MAX_DIGEST_SIZE 64UL /* The longest known is SHA512 */ uint32_t g_uiPort = 8890; /* END_HEADER */ static HITLS_Config *GetHitlsConfigViaVersion(int ver) { HITLS_Config *config; int32_t ret; switch (ver) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); ret = HITLS_CFG_SetCheckKeyUsage(config, false); if (ret != HITLS_SUCCESS) { return NULL; } return config; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); ret = HITLS_CFG_SetCheckKeyUsage(config, false); if (ret != HITLS_SUCCESS) { return NULL; } return config; case HITLS_VERSION_DTLS12: config = HITLS_CFG_NewDTLS12Config(); ret = HITLS_CFG_SetCheckKeyUsage(config, false); if (ret != HITLS_SUCCESS) { return NULL; } return config; default: return NULL; } } int32_t STUB_BSL_UIO_Write(BSL_UIO *uio, const void *data, uint32_t len, uint32_t *writeLen) { (void)uio; (void)data; (void)len; (void)writeLen; return BSL_INTERNAL_EXCEPTION; } /** @ * @test SDV_TLS_CM_KEYUPDATE_FUNC_TC001 * @title HITLS_TLS_Interface_SDV_23_0_5_102 * @precon nan * @brief * 1. Set the version number to tls1.3. After the connection is established, invoke the HITLS_GetKeyUpdateType interface. * Expected result 1 is obtained. * 2. Set the version number to tls1.3. After the connection is created, call hitls_keyupdate successfully, and then call the * HITLS_GetKeyUpdateType interface. Expected result 2 is obtained. * 3. Set the version number to tls1.3. After the connection is created, call the hitls_keyupdate interface to construct an * I/O exception. If the interface fails to be called, call the HITLS_GetKeyUpdateType interface again. Expected * result 3 is obtained. * @expect * 1. The return value is 255. * 2. The return value is 255. * 3. The return value is the configured keyupdate type. @ */ /* BEGIN_CASE */ void SDV_TLS_CM_KEYUPDATE_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ret = HITLS_GetKeyUpdateType(client->ssl); ASSERT_EQ(ret, HITLS_KEY_UPDATE_REQ_END); ret = HITLS_KeyUpdate(client->ssl, HITLS_UPDATE_NOT_REQUESTED); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_SUCCESS); ret = HITLS_GetKeyUpdateType(client->ssl); ASSERT_EQ(ret, HITLS_KEY_UPDATE_REQ_END); FuncStubInfo tmpRpInfo = {0}; STUB_Replace(&tmpRpInfo, BSL_UIO_Write, STUB_BSL_UIO_Write); ret = HITLS_KeyUpdate(client->ssl, HITLS_UPDATE_REQUESTED); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_ERR_IO_EXCEPTION); ret = HITLS_GetKeyUpdateType(client->ssl); ASSERT_EQ(ret, HITLS_UPDATE_REQUESTED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); STUB_Reset(&tmpRpInfo); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface/test_suite_sdv_hlt_tls_cm_1.c
C
unknown
4,979
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include "crypt.h" #include "hitls_crypt_type.h" #include "hitls_crypt_init.h" #define PRF_OUT_LEN 48 /* END_HEADER */ /* BEGIN_CASE */ void SDV_TLS_CRYPT_PRF_TC001(int hashAlgo, Hex *secret, Hex *label, Hex *seed, Hex *expect) { CRYPT_KeyDeriveParameters input = {0}; input.hashAlgo = hashAlgo; input.secret = (uint8_t *)secret->x; input.secretLen = secret->len; input.label = (uint8_t *)label->x; input.labelLen = label->len; input.seed = (uint8_t *)seed->x; input.seedLen = seed->len; input.libCtx = NULL; input.attrName = NULL; uint8_t out[PRF_OUT_LEN] = {0}; HITLS_CryptMethodInit(); ASSERT_TRUE(PRF_OUT_LEN <= expect->len); ASSERT_EQ(SAL_CRYPT_PRF(&input, out, PRF_OUT_LEN), HITLS_SUCCESS); ASSERT_COMPARE("result cmp", out, PRF_OUT_LEN, expect->x, PRF_OUT_LEN); EXIT: return; } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface/test_suite_sdv_tls_crypt.c
C
unknown
1,433
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <unistd.h> #include "securec.h" #include "bsl_sal.h" #include "hitls.h" #include "hitls_config.h" #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "tls.h" #include "hs.h" #include "hs_ctx.h" #include "hs_state_recv.h" #include "conn_init.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "recv_process.h" #include "stub_replace.h" #include "frame_tls.h" #include "frame_msg.h" #include "simulate_io.h" #include "parser_frame_msg.h" #include "pack_frame_msg.h" #include "frame_io.h" #include "frame_link.h" #include "cert.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "hlt.h" #include "sctp_channel.h" #include "logger.h" #define READ_BUF_SIZE (18 * 1024) /* Maximum length of the read message buffer */ typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; bool isServerExtendMasterSecret; bool isSupportRenegotiation; /* Renegotiation support flag */ bool needStopBeforeRecvCCS; /* CCS test, so that the TRY_RECV_FINISH stops before the CCS message is received */ } HandshakeTestInfo; int32_t SendHelloReq(HITLS_Ctx *ctx) { /** Initialize the message buffer. */ uint8_t buf[HS_MSG_HEADER_SIZE] = {0u}; size_t len = HS_MSG_HEADER_SIZE; /** Write records. */ return REC_Write(ctx, REC_TYPE_HANDSHAKE, buf, len); } #define TEST_CLIENT_SEND_FAIL 1 void TestSetCertPath(HLT_Ctx_Config *ctxConfig, char *SignatureType) { if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA1", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA1")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA256")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, RSA_SHA256_PRIV_PATH3, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA384")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA384_EE_PATH, RSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA512", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA512")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA512_EE_PATH, RSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", strlen("CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA256_EE_PATH, ECDSA_SHA256_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", strlen("CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA384_EE_PATH, ECDSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", strlen("CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA512_EE_PATH, ECDSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SHA1", strlen("CERT_SIG_SCHEME_ECDSA_SHA1")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA1_CA_PATH, ECDSA_SHA1_CHAIN_PATH, ECDSA_SHA1_EE_PATH, ECDSA_SHA1_PRIV_PATH, "NULL", "NULL"); } }
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_interface.base.c
C
unknown
5,477
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_interface */ #include <stdio.h> #include "hitls_error.h" #include "hitls_cert.h" #include "hitls.h" #include "hitls_func.h" #include "securec.h" #include "cert_method.h" #include "cert_mgr.h" #include "cert_mgr_ctx.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "session.h" #include "bsl_list.h" #include "bsl_sal.h" #include "bsl_uio.h" #include "alert.h" #include "stub_replace.h" #include "cert_callback.h" #include "crypt_eal_rand.h" #include "hitls_crypt_reg.h" #include "hitls_crypt_init.h" #include "uio_base.h" /* END_HEADER */ #define BUF_MAX_SIZE 4096 int32_t g_uiPort = 18886; static int TestHITLS_VerifyCb(int32_t isPreverifyOk, HITLS_CERT_StoreCtx *storeCtx) { (void)isPreverifyOk; (void)storeCtx; return 0; } static int32_t TestPasswordCb(char *buf, int32_t bufLen, int32_t flag, void *userdata) { (void)flag; char *passwd = NULL; static char pass[] = "123456"; if (userdata != NULL) { passwd = userdata; } else { passwd = pass; } int32_t len = strlen(passwd); if (len > bufLen) { return -1; } memcpy(buf, passwd, len); return len; } static uint32_t ReadFileBuffer(const char *filePath, char *data) { FILE *fd; uint32_t size; uint32_t bytes; fd = fopen(filePath, "rb"); if (fd == NULL) { return 0; } (void)fseek(fd, 0, SEEK_END); size = (uint32_t)ftell(fd); rewind(fd); bytes = (uint32_t)fread(data, 1, size, fd); (void)fclose(fd); if (bytes != size) { return 0; } return bytes; } /* @ * @test UT_TLS_CERT_CM_SetVerifyDepth_API_TC001 * @title The input parameter of the HITLS_SetVerifyDepth interface is replaced. * @precon This test case covers the HITLS_SetVerifyDepth, HITLS_GetVerifyDepth * @brief 1.Invoke the HITLS_SetVerifyDepth interface. The value of ctx is empty and the value of depth is not empty. * Expected result 1 is obtained. *         2.Invoke the HITLS_SetVerifyDepth interface. The values of ctx and depth are not empty. * Expected result 2 is obtained. *         3.Invoke the HITLS_GetVerifyDepth interface. The ctx field is empty and the depth address is not empty. * Expected result 1 is obtained. * @expect  1.Returns HITLS_NULL_INPUT *          2.Returns HITLS_SUCCESS * 3.Returns HITLS_NULL_INPUT @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetVerifyDepth_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; uint32_t depth = 5; int32_t dep = 0; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetVerifyDepth(NULL, depth) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetVerifyDepth(ctx, depth), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetVerifyDepth(ctx, &dep) == HITLS_SUCCESS); ASSERT_EQ(depth, dep); ASSERT_TRUE(HITLS_GetVerifyDepth(NULL, &dep) == HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CFG_SetDefaultPasswordCb_FUNC_001 * @title Set the password callback and set the user data defaultPasswdCbUserdata. * @precon This test case covers the HITLS_CFG_SetDefaultPasswordCb, HITLS_CFG_GetDefaultPasswordCb, * HITLS_CFG_SetDefaultPasswordCbUserdata, HITLS_CFG_GetDefaultPasswordCbUserdata * @brief 1. Create a CTX object. Expected result 1 is obtained. * 2. Set the password callback and set the incorrect user data defaultPasswdCbUserdata. * Expected result 2 is obtained. * @expect  1. Created successfully. * 2. Failed to load the encrypted private key file. @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CFG_SetDefaultPasswordCb_FUNC_001(int version, char *keyFile, char *userdata) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_SetDefaultPasswordCb(tlsConfig, TestPasswordCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetDefaultPasswordCb(tlsConfig) == TestPasswordCb); ASSERT_TRUE(HITLS_CFG_SetDefaultPasswordCbUserdata(tlsConfig, userdata)== HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetDefaultPasswordCbUserdata(tlsConfig) == userdata); #ifdef HITLS_TLS_FEATURE_PROVIDER ASSERT_EQ(HITLS_CFG_ProviderLoadKeyFile(tlsConfig, keyFile, "ASN1", NULL), HITLS_CFG_ERR_LOAD_KEY_FILE); #else ASSERT_EQ(HITLS_CFG_LoadKeyFile(tlsConfig, keyFile, TLS_PARSE_FORMAT_ASN1), HITLS_CFG_ERR_LOAD_KEY_FILE); #endif EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_SetDefaultPasswordCbUserdata_API_TC001 * @title The input parameter of the HITLS_SetDefaultPasswordCbUserdata interface is replaced. * @precon This test case covers the HITLS_SetDefaultPasswordCbUserdata, HITLS_GetDefaultPasswordCbUserdata * @brief 1.Invoke the HITLS_SetDefaultPasswordCbUserdata interface. The value of ctx is empty and the value of * userdata is not empty. Expected result 1 is obtained. *         2.Invoke the HITLS_SetDefaultPasswordCbUserdata interface. The values of ctx and userdata are not empty. * Expected result 2 is obtained. *         3.Invoke the HITLS_GetDefaultPasswordCbUserdata interface and leave ctx blank. Expected result 3 is obtained. * @expect  1.Returns HITLS_NULL_INPUT * 2.Returns HITLS_SUCCESS * 3.Returns NULL             @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetDefaultPasswordCbUserdata_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; char *userData = "123456"; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetDefaultPasswordCbUserdata(NULL, userData) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetDefaultPasswordCbUserdata(ctx, userData) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetDefaultPasswordCbUserdata(NULL) == NULL); ASSERT_TRUE(HITLS_GetDefaultPasswordCbUserdata(ctx) == userData); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CFG_LoadCertFile_API_TC001 * @title HITLS_CFG_LoadCertFile Loading a Device Certificate from a File * @precon This test case covers the HITLS_CFG_LoadCertFile, HITLS_CFG_SetDefaultPasswordCbUserdata, * HITLS_CFG_GetDefaultPasswordCbUserdata, HITLS_CFG_LoadKeyFile * @brief 1. Apply for a configuration file. Expected result 1 is obtained. * 2. Load an incorrect path. Expected result 2 is obtained. * 3. Use the same keyword "123456" for mac word and pass word. Expected result 3 is obtained. * @expect  1. The application is successful. * 2. Failed to load the certificate. * 3. The certificate is loaded successfully. @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CFG_LoadCertFile_API_TC001(int version, char *certFile1, char *certFile2, char *keyFile2, char *userdata) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_EQ( HITLS_CFG_LoadCertFile(tlsConfig, certFile1, TLS_PARSE_FORMAT_ASN1), HITLS_CFG_ERR_LOAD_CERT_FILE); ASSERT_TRUE(HITLS_CFG_SetDefaultPasswordCbUserdata(tlsConfig, userdata) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetDefaultPasswordCbUserdata(tlsConfig) == userdata); ASSERT_TRUE(HITLS_CFG_LoadCertFile(tlsConfig, certFile2, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); #ifdef HITLS_TLS_FEATURE_PROVIDER ASSERT_TRUE(HITLS_CFG_ProviderLoadKeyFile(tlsConfig, keyFile2, "ASN1", NULL) == HITLS_SUCCESS); #else ASSERT_TRUE(HITLS_CFG_LoadKeyFile(tlsConfig, keyFile2, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); #endif EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CFG_LoadCertBuffer_FUNC_001 * @title HITLS_CFG_LoadCertBuffer Loads and Obtains the Device Certificate from the Buffer * @precon nan * @brief 1. Create a CTX object. Expected result 1 is obtained. * 2. In the local context, the store is not initialized. Invoke HITLS_CFG_GetCertificate to obtain the device * certificate. Expected result 2 is obtained. * 3. Call the interface to convert the certificate file into a buffer. Expected result 3 is obtained. * 4. Delete one byte from the buffer, that is, buffer1. Expected result 4 is obtained. * 5. Add one byte to the buffer, that is, buffer2. Expected result 5 is obtained. * 6. Call the interface to set the device certificate through buffer1. Expected result 6 is obtained. * 7. Call the interface to set the device certificate through buffer2. Expected result 7 is obtained. * 8. Call the interface to set the device certificate through the buffer. Expected result 8 is obtained. * 9. Call the interface repeatedly to set the device certificate through the buffer. Expected result 9 is * obtained. * @expect 1. Created successfully. * 2. The obtained content is empty. * 3. The file is converted successfully. * 4. Deleted successfully. * 5. Adding succeeded. * 6. Failed to load the device certificate. * 7. Failed to load the device certificate. * 8. Succeeded in loading the device certificate. * 9. Failed to load the device certificate. @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CFG_LoadCertBuffer_FUNC_001(int version, char *certPath) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); uint8_t buf[BUF_MAX_SIZE] = {0}; uint32_t bufLen = ReadFileBuffer(certPath, (char *)buf); ASSERT_TRUE(buf != NULL); ASSERT_TRUE(bufLen <= BUF_MAX_SIZE); uint8_t buf2[BUF_MAX_SIZE] = {0}; (void)memcpy_s(buf2, bufLen, buf, bufLen); buf2[bufLen - 1] = 'b'; buf2[bufLen] = 0; uint8_t buf1[BUF_MAX_SIZE] = {0}; (void)memcpy_s(buf1, bufLen, buf, bufLen); buf1[bufLen - 2] = 0; ASSERT_TRUE(HITLS_CFG_LoadCertBuffer(tlsConfig, buf, bufLen, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); ASSERT_EQ( HITLS_CFG_LoadCertBuffer(tlsConfig, buf1, bufLen - 1, TLS_PARSE_FORMAT_ASN1), HITLS_CFG_ERR_LOAD_CERT_BUFFER); ASSERT_TRUE(HITLS_CFG_LoadCertBuffer(tlsConfig, buf2, bufLen + 1, TLS_PARSE_FORMAT_ASN1) != HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_LoadCertBuffer(tlsConfig, buf, bufLen, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_LoadCertFile_API_TC001 * @title The input parameter of the HITLS_LoadCertFile interface is replaced. * @precon nan * @brief 1.Invoke the HITLS_LoadCertFile interface. The ctx field is empty, the device certificate file name is not * empty, and the certificate format is PEM. Expected result 1 is obtained. * 2.Invoke the HITLS_LoadCertFile interface. The ctx parameter is not empty, the device certificate file name * is not empty, and the certificate format is PEM. Expected result 2 is obtained. * @expect  1.Returns HITLS_NULL_INPUT *          2.Returns HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_LoadCertFile_API_TC001(int version, char *certFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_LoadCertFile(NULL, NULL, TLS_PARSE_FORMAT_ASN1) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_LoadCertFile(ctx, certFile, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_LoadCertBuffer_API_TC001 * @title The input parameter of the HITLS_LoadCertBuffer interface is replaced. * @precon nan * @brief 1.Invoke the HITLS_LoadCertBuffer interface. The ctx field is empty, the certificate buffer is not empty, the * buffer length is the actual buffer length, and the certificate format is PEM. Expected result 1 is * displayed. * 2.Invoke the HITLS_LoadCertBuffer interface. Ensure that ctx is not empty, the device certificate file name * is not empty, and the certificate format is PEM. Expected result 2 is obtained. * @expect  1.Returns HITLS_NULL_INPUT *          2.Returns HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_LoadCertBuffer_API_TC001(int version, char *certFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; uint8_t certBuffer[BUF_MAX_SIZE] = {0}; uint32_t certBuffLen = ReadFileBuffer(certFile, (char *)certBuffer); ASSERT_TRUE(certBuffLen <= BUF_MAX_SIZE); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_LoadCertBuffer(NULL, certBuffer, certBuffLen, TLS_PARSE_FORMAT_ASN1) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_LoadCertBuffer(ctx, certBuffer, certBuffLen, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CFG_LoadKeyBuffer_FUNC_TC001 * @title Load the private key from buffer by using HITLS_CFG_LoadKeyBuffer interface * @precon nan * @brief 1. Apply for a configuration file. Expected result 1 is obtained * 2. Call the API to convert the certificate file into a buffer. Expected result 2 is displayed * 3. Delete one byte from the buffer, that is, buf1. Expected result 3 is obtained * 4. Add one byte to the buffer, that is, buf2. Expected result 4 * 5. Call the interface to load the private key through buf1. Expected result 5 * 6. Call the interface to load the private key through buf2. Expected result 6 * 7. Invoke the interface to load the private key through the buffer. Expected result 7 * 8. Invoke the interface repeatedly to load the private key through the buffer. Expected result 8 is obtained * @expect  1. The application is successful. * 2. The file is converted successfully. * 3. The deletion is successful. * 4. The addition is successful. * 5. The private key fails to be loaded. * 6. The private key success to be loaded. * 7. The private key is loaded. * 8. The private key fails to be loaded @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CFG_LoadKeyBuffer_FUNC_TC001(int version, char *keyPath) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); uint8_t buf[BUF_MAX_SIZE] = {0}; uint32_t bufLen = ReadFileBuffer(keyPath, (char *)buf); ASSERT_TRUE(buf != NULL); ASSERT_TRUE(bufLen <= BUF_MAX_SIZE); uint8_t buf2[BUF_MAX_SIZE] = {0}; memcpy_s(buf2, bufLen, buf, bufLen); buf2[bufLen - 1] = 'a'; buf2[bufLen] = 0; uint8_t buf1[BUF_MAX_SIZE] = {0}; memcpy_s(buf1, bufLen, buf, bufLen); buf1[bufLen - 2] = 0; ASSERT_TRUE(HITLS_CFG_LoadKeyBuffer(tlsConfig, buf, bufLen, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); ASSERT_EQ( HITLS_CFG_LoadKeyBuffer(tlsConfig, buf1, bufLen - 1, TLS_PARSE_FORMAT_ASN1), HITLS_CFG_ERR_LOAD_KEY_BUFFER); ASSERT_EQ( HITLS_CFG_LoadKeyBuffer(tlsConfig, buf2, bufLen + 1, TLS_PARSE_FORMAT_ASN1), HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_LoadKeyBuffer(tlsConfig, buf, bufLen, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_LoadKeyFile_API_TC001 * @title The error input parameter for HITLS_LoadKeyFile * @precon nan * @brief 1.Invoke the HITLS_LoadKeyFile interface. The ctx field is empty, the private key file name is not empty, * and the private key format is PEM. Expected result 1 * 2.Invoke the HITLS_LoadKeyFile interface. The ctx field is not empty. The private key file name is not empty * and the private key is in PEM format. Expected result 2 is obtained * @expect 1.Back HITLS_NULL_INPUT *         2.Back HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_LoadKeyFile_API_TC001(int version, char *keyFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_LoadKeyFile(NULL, keyFile, TLS_PARSE_FORMAT_ASN1) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_LoadKeyFile(ctx, keyFile, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_SetAndGetCert_FUNC_TC001 * @title Set and get verify result * @precon nan * @brief 1. Construct the CTX configuration and initialize the session and certificate management. Expected results 1 * 2. Call HITLS_GetVerifyResult to query the peer certificate verification result of the current context. Expected result 2 * 3. Call HITLS_SetVerifyResult to set the peer certificate verification result of the current context. Expected result 3 * 4. Call HITLS_GetVerifyResult to query the peer certificate verification result of the current context. Expected result 4 is obtained * @expect 1. Initialization succeeded. * 2. The verification result is 0. * 3. The setting result is successful. * 4. The verification result is the set value @ */ /* BEGIN_CASE */ void UT_TLS_SetAndGetCert_FUNC_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; HITLS_ERROR result; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetVerifyResult(ctx, &result) == HITLS_SUCCESS); ASSERT_EQ(result, HITLS_X509_V_OK); ASSERT_TRUE(HITLS_SetVerifyResult(ctx, HITLS_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetVerifyResult(ctx, &result) == HITLS_SUCCESS); ASSERT_TRUE(result == HITLS_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_LoadKeyBuffer_API_TC001 * @title The error input parameter for HITLS_LoadKeyBuffer * @precon nan * @brief 1. Invoke the HITLS_LoadKeyBuffer interface. The ctx field is empty, the private key buffer is not empty, * the buffer length is the actual buffer length, and the private key format is PEM. Expected result 1 is * displayed. * 2. Invoke the HITLS_LoadKeyBuffer interface. The ctx and private key buffer are not empty, the buffer length * is the actual buffer length, and the private key format is pem. The expected result is 1 * @expect 1. HITLS_NULL_INPUT is returned * 2. HITLS_SUCCESS is returned @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_LoadKeyBuffer_API_TC001(int version, char *keyFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; uint8_t keyBuffer[BUF_MAX_SIZE] = {0}; uint32_t keyBuffLen = ReadFileBuffer(keyFile, (char *)keyBuffer); ASSERT_TRUE(keyBuffLen <= BUF_MAX_SIZE); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_LoadKeyBuffer(NULL, keyBuffer, keyBuffLen, TLS_PARSE_FORMAT_ASN1) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_LoadKeyBuffer(ctx, keyBuffer, keyBuffLen, TLS_PARSE_FORMAT_ASN1) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CFG_SetTlcpCertificate_FUNC_001 * If an unrecognized record type is received, ignore it. * @title There are only four types of record layers. * @precon Test Content: Record layer protocols include: handshake, alarm, and password specification change. * To support protocol extensions, the record layer protocol may support other record types. * Any new record types should be deassigned in addition to the Content Type values assigned for the types * described above. * In this test case, interface HITLS_CFG_SetTlcpCertificate, HITLS_CFG_SetTlcpPrivateKey is invoked at the * bottom layer. * @brief After the link is set up, the server receives abnormal messages (the recordType is 99) after receiving * app data. The server is expected to return an alert. * @expect 1. HITLS_REC_ERR_RECV_UNEXPECTED_MSG is returned @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CFG_SetTlcpCertificate_FUNC_001(void) { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(tlsConfig != NULL); uint16_t cipherSuite[] = {HITLS_ECDHE_SM4_CBC_SM3, HITLS_ECC_SM4_CBC_SM3}; HITLS_CFG_SetCipherSuites(tlsConfig, cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, true); server = FRAME_CreateTLCPLink(tlsConfig, BSL_UIO_TCP, false); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t dataBuf[] = "Hello World!"; uint8_t readBuf[READ_BUF_SIZE]; uint32_t readbytes; uint32_t writeLen; ASSERT_EQ(HITLS_Write(client->ssl, dataBuf, sizeof(dataBuf), &writeLen), HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); FrameUioUserData *ioServerData = BSL_UIO_GetUserData(server->io); ioServerData->recMsg.msg[0] = 0x99u; ASSERT_EQ(HITLS_Read(server->ssl, readBuf, READ_BUF_SIZE, &readbytes), HITLS_REC_ERR_RECV_UNEXPECTED_MSG); ALERT_Info info = { 0 }; ALERT_GetInfo(server->ssl, &info); ASSERT_EQ(info.flag, ALERT_FLAG_SEND); ASSERT_EQ(info.level, ALERT_LEVEL_FATAL); ASSERT_EQ(info.description, ALERT_UNEXPECTED_MESSAGE); EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CFG_SetVerifyCb_API_TC001 * @title HITLS_CFG_SetVerifyCb interface input parameter test * @precon This test case covers the HITLS_CFG_SetVerifyCb, HITLS_CFG_GetVerifyCb * @brief 1. Invoke the HITLS_CFG_SetVerifyCb interface. Input empty tlsConfig and non-empty certificate verification * callback. Expected result 1 * 2. Invoke the HITLS_CFG_SetVerifyCb interface. Input non-empty tlsConfig and non-empty certificate * verification callback. Expected result 3 * 3. Invoke the HITLS_CFG_GetVerifyCb interface. Input empty tlsConfig, Expected result 2 * 4. Invoke the HITLS_CFG_SetVerifyCb interface. Input empty tlsConfig->certMgrCtx, and non-empty certificate * verification callback, Expected result 1 * 5. Invoke the HITLS_CFG_GetVerifyCb interface. Input empty tlsConfig->certMgrCtx, Expected result 2 * Expected result 2 * @expect 1. Return HITLS_NULL_INPUT * 2. Return NULL * 3. Return HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CFG_SetVerifyCb_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_SetVerifyCb(NULL, TestHITLS_VerifyCb) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetVerifyCb(tlsConfig, TestHITLS_VerifyCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetVerifyCb(tlsConfig) == TestHITLS_VerifyCb); ASSERT_TRUE(HITLS_CFG_GetVerifyCb(NULL) == NULL); SAL_CERT_MgrCtxFree(tlsConfig->certMgrCtx); tlsConfig->certMgrCtx = NULL; ASSERT_TRUE(HITLS_CFG_SetVerifyCb(tlsConfig, TestHITLS_VerifyCb) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetVerifyCb(tlsConfig) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_SetVerifyCb_API_TC001 * @title HITLS_SetVerifyCb interface input parameter test * @precon This test case covers the HITLS_SetVerifyCb, HITLS_GetVerifyCb * @brief 1.Invoke the HITLS_SetVerifyCb interface. Input empty ctx and non-empty certificate verification * callback. Expected result 1 * 2.Invoke the HITLS_SetVerifyCb interface. Input non-empty ctx and non-empty certificate verification * callback. Expected result 2 * 3.Invoke the HITLS_GetVerifyCb interface. Input empty ctx, Expected result 3 * @expect 1.Return HITLS_NULL_INPUT * 2.Return HITLS_SUCCESS * 3.Return NULL @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetVerifyCb_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetVerifyCb(NULL, TestHITLS_VerifyCb) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetVerifyCb(ctx, TestHITLS_VerifyCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetVerifyCb(NULL) == NULL); ASSERT_TRUE(HITLS_GetVerifyCb(ctx) == TestHITLS_VerifyCb); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* * @test UT_TLS_CERT_GET_CERTIFICATE_API_TC001 * * @title Overwrite the input parameter of the HITLS_GetCertificate interface. * * @brief * 1. Invoke the HITLS_GetCertificate interface and leave ctx blank. Expected result 1. * 2. Invoke the HITLS_GetPeerCertificate interface and leave ctx blank. Expected result 1. * 3. Invoke the HITLS_GetPeerCertificate interface. The value of ctx is not empty and the value of ctx->session is empty. * Expected result 1. * 4. Invoke the HITLS_GetPeerCertChain interface and leave ctx blank. Expected result 1. * 5. Invoke the HITLS_GetPeerCertChain interface. The value of ctx is not empty and the value of ctx->session is empty. * Expected result 1 . * @expect 1. Return NULL. * @prior Level 1 * @auto TRUE */ /* BEGIN_CASE */ void UT_TLS_CERT_GET_CERTIFICATE_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetCertificate(NULL) == NULL); ASSERT_TRUE(HITLS_GetPeerCertificate(NULL) == NULL); ASSERT_TRUE(HITLS_GetPeerCertChain(NULL) == NULL); ctx->session = NULL; ASSERT_TRUE(HITLS_GetPeerCertificate(ctx) == NULL); ASSERT_TRUE(HITLS_GetPeerCertChain(ctx) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ void StubListDataDestroy(void *data) { BSL_SAL_FREE(data); return; } /* @ * @test UT_TLS_CERT_GET_CALIST_FUNC_TC001 * * @title Obtain the peer certificate chain and trusted CA list. * * @brief * 1. Construct the CTX configuration. Expected result 1. * 2. Invoke HITLS_GetPeerCertChain to obtain the peer certificate chain. Expected result 2. * 3. Configure a certificate management instance for the session instance. Expected result 3. * 4. Add the session instance to the SSL instance. Expected result 4. * 5. If no certificate is loaded to the peer end, call HITLS_GetPeerCertificate to obtain the peer certificate. * Expected result 5. * 6. Create a peer certificate management instance and a certificate chain. Expected result 6. * 7. Add the created certificates to the certificate linked list one by one. Expected result 7. * 8. Invoke HITLS_GetPeerCertChain to obtain the peer certificate chain. Expected result 8. * 9. Invoke the HITLS_GetPeerCAList client certificate authority (CA) list. Expected result 9. * @expect * 1. The creation is successful. * 2. Obtaining failed. The session is empty. * 3. The setting is successful, and the interface returns 0. * 4. If the setting is successful, the interface returns 0. * 5. Failed to obtain the certificate. The certificate is empty. * 6. The peerCert and certificate chain are successfully created. * 7. The interface returns 0. * 8. The certificate successfully. The obtained peer certificate chain is correct. The obtained cert is * correct. * 9. The obtained CA certificate list is correct. The obtained cert is correct. @ */ /* BEGIN_CASE */ void UT_TLS_CERT_GET_CALIST_FUNC_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ctx->isClient = true; HITLS_Session *session = HITLS_SESS_New(); ASSERT_TRUE(session != NULL); CERT_Pair *peerCert = (CERT_Pair *)BSL_SAL_Calloc(1u, sizeof(CERT_Pair)); HITLS_CERT_X509 *cert1 = (HITLS_CERT_X509 *)BSL_SAL_Calloc(1u, sizeof(HITLS_CERT_X509)); HITLS_CERT_X509 *cert2 = (HITLS_CERT_X509 *)BSL_SAL_Calloc(1u, sizeof(HITLS_CERT_X509)); HITLS_CERT_X509 *cert3 = (HITLS_CERT_X509 *)BSL_SAL_Calloc(1u, sizeof(HITLS_CERT_X509)); peerCert->chain = (HITLS_CERT_Chain *)BSL_LIST_New(sizeof(HITLS_CERT_X509 *)); ASSERT_TRUE(peerCert->chain != NULL); HITLS_CERT_Chain *certChain = peerCert->chain; int32_t ret = BSL_LIST_AddElement((BslList *)certChain, cert1, BSL_LIST_POS_END); ASSERT_TRUE(ret == 0); ret = BSL_LIST_AddElement((BslList *)certChain, cert2, BSL_LIST_POS_END); ASSERT_TRUE(ret == 0); ret = BSL_LIST_AddElement((BslList *)certChain, cert3, BSL_LIST_POS_END); ASSERT_TRUE(ret == 0); ret = SESS_SetPeerCert(session, peerCert, false); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetSession(ctx, session) == HITLS_SUCCESS); HITLS_CERT_Chain *getCertChain = HITLS_GetPeerCertChain(ctx); ASSERT_TRUE(getCertChain != NULL); HITLS_TrustedCAList *tmpCAList = ctx->peerInfo.caList; HITLS_TrustedCANode *newNode1 = (HITLS_TrustedCANode *)BSL_SAL_Calloc(1, sizeof(HITLS_TrustedCANode)); ASSERT_TRUE(newNode1 != NULL); newNode1->caType = HITLS_TRUSTED_CA_X509_NAME; newNode1->data = NULL; newNode1->dataSize = 0; HITLS_TrustedCANode *newNode2 = (HITLS_TrustedCANode *)BSL_SAL_Calloc(1, sizeof(HITLS_TrustedCANode)); ASSERT_TRUE(newNode2 != NULL); newNode2->caType = HITLS_TRUSTED_CA_X509_NAME; newNode2->data = NULL; newNode2->dataSize = 0; ret = BSL_LIST_AddElement((BslList *)tmpCAList, newNode1, BSL_LIST_POS_END); ASSERT_TRUE(ret == 0); ret = BSL_LIST_AddElement((BslList *)tmpCAList, newNode2, BSL_LIST_POS_END); ASSERT_TRUE(ret == 0); HITLS_TrustedCAList *caList = HITLS_GetPeerCAList(ctx); ASSERT_TRUE(caList != NULL); ASSERT_EQ(caList->count, 2); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); BSL_LIST_DeleteAll((BslList *)peerCert->chain, StubListDataDestroy); HITLS_SESS_Free(session); } /* END_CASE */ /* @ * @test UT_TLS_CRL_LOAD_FILE_FUNC_TC001 * @title HITLS_CFG_LoadCrlFile interface functional test * @precon This test case covers the HITLS_CFG_LoadCrlFile interface @ */ /* BEGIN_CASE */ void UT_TLS_CRL_LOAD_FILE_FUNC_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(config != NULL); const char *crlPath = "../testdata/tls/certificate/der/ed25519/ed25519.crl.der"; // Test successful CRL file loading int32_t ret = HITLS_CFG_LoadCrlFile(config, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test invalid parameters ret = HITLS_CFG_LoadCrlFile(NULL, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); ret = HITLS_CFG_LoadCrlFile(config, NULL, TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); ret = HITLS_CFG_LoadCrlFile(config, "", TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CRL_LOAD_BUFFER_FUNC_TC001 * @title HITLS_CFG_LoadCrlBuffer interface functional test * @precon This test case covers the HITLS_CFG_LoadCrlBuffer interface @ */ /* BEGIN_CASE */ void UT_TLS_CRL_LOAD_BUFFER_FUNC_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(config != NULL); const char *crlPath = "../testdata/tls/certificate/der/ed25519/ed25519.crl.der"; // Read CRL file content FILE *file = fopen(crlPath, "rb"); ASSERT_TRUE(file != NULL); fseek(file, 0, SEEK_END); long fileSize = ftell(file); fseek(file, 0, SEEK_SET); ASSERT_TRUE(fileSize > 0); uint8_t *crlData = (uint8_t *)BSL_SAL_Malloc(fileSize); ASSERT_TRUE(crlData != NULL); size_t bytesRead = fread(crlData, 1, fileSize, file); fclose(file); ASSERT_EQ(bytesRead, (size_t)fileSize); // Test successful CRL buffer loading int32_t ret = HITLS_CFG_LoadCrlBuffer(config, crlData, fileSize, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test invalid parameters ret = HITLS_CFG_LoadCrlBuffer(NULL, crlData, fileSize, TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); ret = HITLS_CFG_LoadCrlBuffer(config, NULL, fileSize, TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); ret = HITLS_CFG_LoadCrlBuffer(config, crlData, 0, TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); EXIT: BSL_SAL_Free(crlData); HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CRL_CTX_LOAD_FILE_FUNC_TC001 * @title HITLS_LoadCrlFile interface functional test * @precon This test case covers the HITLS_LoadCrlFile runtime context interface @ */ /* BEGIN_CASE */ void UT_TLS_CRL_CTX_LOAD_FILE_FUNC_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); const char *crlPath = "../testdata/tls/certificate/der/ed25519/ed25519.crl.der"; // Test successful CRL file loading in context int32_t ret = HITLS_LoadCrlFile(ctx, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test invalid parameters ret = HITLS_LoadCrlFile(NULL, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); EXIT: HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CRL_CTX_LOAD_BUFFER_FUNC_TC001 * @title HITLS_LoadCrlBuffer interface functional test * @precon This test case covers the HITLS_LoadCrlBuffer runtime context interface @ */ /* BEGIN_CASE */ void UT_TLS_CRL_CTX_LOAD_BUFFER_FUNC_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); const char *crlPath = "../testdata/tls/certificate/der/ed25519/ed25519.crl.der"; // Read CRL file content FILE *file = fopen(crlPath, "rb"); ASSERT_TRUE(file != NULL); fseek(file, 0, SEEK_END); long fileSize = ftell(file); fseek(file, 0, SEEK_SET); ASSERT_TRUE(fileSize > 0); uint8_t *crlData = (uint8_t *)BSL_SAL_Malloc(fileSize); ASSERT_TRUE(crlData != NULL); size_t bytesRead = fread(crlData, 1, fileSize, file); fclose(file); ASSERT_EQ(bytesRead, (size_t)fileSize); // Test successful CRL buffer loading in context int32_t ret = HITLS_LoadCrlBuffer(ctx, crlData, fileSize, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test invalid parameters ret = HITLS_LoadCrlBuffer(NULL, crlData, fileSize, TLS_PARSE_FORMAT_ASN1); ASSERT_NE(ret, HITLS_SUCCESS); EXIT: BSL_SAL_Free(crlData); HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CRL_CFG_CLEAR_FUNC_TC001 * @title HITLS_CFG_ClearVerifyCrls interface functional test * @precon This test case covers the HITLS_CFG_ClearVerifyCrls interface @ */ /* BEGIN_CASE */ void UT_TLS_CRL_CFG_CLEAR_FUNC_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(config != NULL); const char *crlPath = "../testdata/tls/certificate/der/ed25519/ed25519.crl.der"; // Load CRL file first int32_t ret = HITLS_CFG_LoadCrlFile(config, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test successful CRL clearing ret = HITLS_CFG_ClearVerifyCrls(config); ASSERT_EQ(ret, HITLS_SUCCESS); // Load CRL again to verify clearing worked ret = HITLS_CFG_LoadCrlFile(config, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test invalid parameter ret = HITLS_CFG_ClearVerifyCrls(NULL); ASSERT_NE(ret, HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CRL_CTX_CLEAR_FUNC_TC001 * @title HITLS_ClearVerifyCrls interface functional test * @precon This test case covers the HITLS_ClearVerifyCrls runtime context interface @ */ /* BEGIN_CASE */ void UT_TLS_CRL_CTX_CLEAR_FUNC_TC001(void) { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLSConfig(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); const char *crlPath = "../testdata/tls/certificate/der/ed25519/ed25519.crl.der"; // Load CRL file first int32_t ret = HITLS_LoadCrlFile(ctx, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test successful CRL clearing ret = HITLS_ClearVerifyCrls(ctx); ASSERT_EQ(ret, HITLS_SUCCESS); // Load CRL again to verify clearing worked ret = HITLS_LoadCrlFile(ctx, crlPath, TLS_PARSE_FORMAT_ASN1); ASSERT_EQ(ret, HITLS_SUCCESS); // Test invalid parameter ret = HITLS_ClearVerifyCrls(NULL); ASSERT_NE(ret, HITLS_SUCCESS); EXIT: HITLS_Free(ctx); HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CRL_VERIFICATION_HANDSHAKE_TC001 * @title CRL verification in TLS handshake functional test * @precon This test case covers CRL functionality during TLS handshake process @ */ /* BEGIN_CASE */ void UT_TLS_CRL_VERIFICATION_HANDSHAKE_TC001(void) { HitlsInit(); FRAME_Init(); // Test data paths const char *serverCertPath = "../testdata/tls/certificate/der/ed25519/ed25519.end.der"; const char *serverKeyPath = "../testdata/tls/certificate/der/ed25519/ed25519.end.key.der"; const char *intCaPath = "../testdata/tls/certificate/der/ed25519/ed25519.intca.der"; const char *caCertPath = "../testdata/tls/certificate/der/ed25519/ed25519.ca.der"; const char *crlPath = "../testdata/tls/certificate/der/ed25519/ed25519.crl.der"; // Test 1: Handshake without CRL - should succeed HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); // Configure server with certificate and key ASSERT_EQ(HITLS_CFG_LoadCertFile(config, serverCertPath, TLS_PARSE_FORMAT_ASN1), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_LoadKeyFile(config, serverKeyPath, TLS_PARSE_FORMAT_ASN1), HITLS_SUCCESS); HITLS_CERT_X509 *caCert = HITLS_CFG_ParseCert(config, (const uint8_t *)caCertPath, strlen(caCertPath), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(caCert != NULL); ASSERT_EQ(HITLS_CFG_AddCertToStore(config, caCert, TLS_CERT_STORE_TYPE_DEFAULT, false), HITLS_SUCCESS); caCert = HITLS_CFG_ParseCert(config, (const uint8_t *)intCaPath, strlen(intCaPath), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(caCert != NULL); ASSERT_EQ(HITLS_CFG_AddCertToStore(config, caCert, TLS_CERT_STORE_TYPE_DEFAULT, false), HITLS_SUCCESS); FRAME_LinkObj *client = FRAME_CreateLinkBase(config, BSL_UIO_TCP, false); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLinkBase(config, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); // Attempt handshake without CRL - should succeed ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); FRAME_FreeLink(client); FRAME_FreeLink(server); server = FRAME_CreateLinkBase(config, BSL_UIO_TCP, false); ASSERT_TRUE(server != NULL); ASSERT_EQ(HITLS_CFG_LoadCrlFile(config, crlPath, TLS_PARSE_FORMAT_ASN1), HITLS_SUCCESS); client = FRAME_CreateLinkBase(config, BSL_UIO_TCP, false); ASSERT_TRUE(client != NULL); ASSERT_NE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_SetVerifyFlags_API_TC001 * @title The input parameter of the HITLS_CFG_SetVerifyFlags interface is replaced. * @precon This test case covers the HITLS_CFG_SetVerifyFlags, HITLS_CFG_GetVerifyFlags * @brief 1.Invoke the HITLS_CFG_SetVerifyFlags interface. The value of ctx is empty and the value of flags is 5. * Expected result 1 is obtained. *         2.Invoke the HITLS_CFG_SetVerifyFlags interface. The values of ctx and flags are not empty. * Expected result 2 is obtained. *         3.Invoke the HITLS_CFG_GetVerifyFlags interface. The ctx field is empty and the ff address is not empty. * Expected result 1 is obtained. * 4.Invoke the HITLS_CFG_GetVerifyFlags interface. The values of ctx and ff address are not empty. * Expected result 2 is obtained. * @expect  1.Returns HITLS_NULL_INPUT *          2.Returns HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetVerifyFlags_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; uint32_t flags = 5; uint32_t ff = 0; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_SetVerifyFlags(NULL, flags) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_CFG_SetVerifyFlags(tlsConfig, flags), HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetVerifyFlags(tlsConfig, &ff) == HITLS_SUCCESS); ASSERT_EQ(flags, ff); ASSERT_TRUE(HITLS_CFG_GetVerifyFlags(NULL, &ff) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetVerifyFlags(tlsConfig, NULL) == HITLS_NULL_INPUT); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); flags = 10; uint32_t ff2 = 0; ASSERT_TRUE(HITLS_SetVerifyFlags(NULL, flags) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetVerifyFlags(ctx, flags), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetVerifyFlags(ctx, &ff2) == HITLS_SUCCESS); ASSERT_EQ((flags | ff), ff2); ASSERT_TRUE(HITLS_GetVerifyFlags(NULL, &ff2) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetVerifyFlags(ctx, NULL) == HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_sdv_frame_cert_interface.c
C
unknown
43,911
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ /* INCLUDE_BASE test_suite_interface */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <linux/limits.h> #include <unistd.h> #include <stdbool.h> #include "hitls_error.h" #include "hitls_cert.h" #include "hitls.h" #include "hitls_func.h" #include "securec.h" #include "cert_method.h" #include "cert_mgr.h" #include "cert_mgr_ctx.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "session.h" #include "bsl_sal.h" #include "bsl_uio.h" #include "alert.h" #include "stub_replace.h" #include "cert_callback.h" #include "crypt_eal_rand.h" #include "hitls_crypt_reg.h" #include "hitls_crypt_init.h" #include "uio_base.h" #include "hlt_type.h" #include "hlt.h" #include "hitls_cert_type.h" #include "hitls_type.h" #include "hitls_cert_reg.h" #include "hitls_config.h" #include "hitls_cert_init.h" #include "bsl_log.h" #include "bsl_err.h" #include "logger.h" #include "tls_config.h" #include "tls.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "bsl_obj.h" #include "bsl_errno.h" #include "hitls_x509_adapt.h" #include "hitls_pki_x509.h" /* END_HEADER */ #define BUF_MAX_SIZE 4096 int32_t g_uiPort = 18886; HITLS_CERT_X509 *HiTLS_X509_LoadCertFile(HITLS_Config *tlsCfg, const char *file); /* @ * @test UT_TLS_CERT_CM_SetVerifyStore_API_TC001 * @title The input parameters of the HITLS_SetVerifyStore and HITLS_GetVerifyStore interfaces are replaced. * @precon nan * @brief 1.Invoke the HITLS_SetVerifyStore interface. The value of ctx is empty and the value of store for the CA * certificate is not empty. Perform shallow copy. Expected result 1 is obtained. *          2.Invoke the HITLS_SetVerifyStore interface. Set ctx and CA certificate store to a value that is not empty. * Expected result 2 is obtained. *          3.Invoke the HITLS_GetVerifyStore interface and leave tlsConfig blank. Expected result 3 is obtained. * @expect  1.Returns HITLS_NULL_INPUT *          2.Returns HITLS_SUCCESS * 3.Returns NULL @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetVerifyStore_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; HITLS_CERT_Store *verifyStore = HITLS_X509_Adapt_StoreNew(); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetVerifyStore(NULL, verifyStore, false) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetVerifyStore(ctx, verifyStore, true), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetVerifyStore(ctx) == verifyStore); ASSERT_TRUE(HITLS_GetVerifyStore(NULL) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); HITLS_X509_StoreCtxFree(verifyStore); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_SetChainStore_API_TC001 * @title The input parameters of the HITLS_SetChainStore and HITLS_GetChainStore interfaces are replaced. * @precon This test case covers the HITLS_SetChainStore、HITLS_GetChainStore * @brief 1.Invoke the HITLS_SetChainStore interface. The ctx field is empty and the certificate chain store is not * empty. Perform shallow copy. Expected result 1 is obtained. *         2.Invoke the HITLS_SetChainStore interface. The value of ctx is not empty and the value of store in the * certificate chain is not empty. Perform shallow copy. Expected result 2 is obtained. *         3.Invoke the HITLS_GetChainStore interface and leave tlsConfig empty. Expected result 3 is obtained. * @expect  1.Returns HITLS_NULL_INPUT * 2.Returns HITLS_SUCCESS *          3.Returns NULL @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetChainStore_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; HITLS_CERT_Store *chainStore = HITLS_X509_Adapt_StoreNew(); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetChainStore(NULL, chainStore, false) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetChainStore(ctx, chainStore, false), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetChainStore(ctx) == chainStore); ASSERT_TRUE(HITLS_GetChainStore(NULL) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_SetCertStore_API_TC001 * @title The input parameter of the HITLS_SetCertStore interface is replaced. * @precon This test case covers the HITLS_SetCertStore、HITLS_GetCertStore * @brief 1.Invoke the HITLS_SetCertStore interface. The value of ctx is empty, and the value of store for the trust * certificate is not empty. Perform shallow copy. Expected result 1 is obtained. *         2.Invoke the HITLS_SetCertStore interface. Ensure that ctx and store of the trust certificate are not empty. * Perform shallow copy. Expected result 2 is obtained. *         3.Invoke the HITLS_GetCertStore interface and leave ctx blank. Expected result 3 is obtained. * @expect  1.Returns HITLS_NULL_INPUT * 2.Returns HITLS_SUCCESS *          3.Returns NULL @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetCertStore_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; HITLS_CERT_Store *certStore = HITLS_X509_Adapt_StoreNew(); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetCertStore(NULL, certStore, false) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetCertStore(ctx, certStore, false), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetCertStore(ctx) == certStore); ASSERT_TRUE(HITLS_GetCertStore(NULL) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_CM_SetDefaultPasswordCbUserdata_API_TC001 * @title The input parameter of the HITLS_SetDefaultPasswordCbUserdata interface is replaced. * @precon This test case covers the HITLS_SetDefaultPasswordCbUserdata、HITLS_GetDefaultPasswordCbUserdata * @brief 1.Invoke the HITLS_SetDefaultPasswordCbUserdata interface. The value of ctx is empty and the value of * userdata is not empty. Expected result 1 is obtained. *         2.Invoke the HITLS_SetDefaultPasswordCbUserdata interface. The values of ctx and userdata are not empty. * Expected result 2 is obtained. *         3.Invoke the HITLS_GetDefaultPasswordCbUserdata interface and leave ctx blank. Expected result 3 is obtained. * @expect  1.Returns HITLS_NULL_INPUT * 2.Returns HITLS_SUCCESS * 3.Returns NULL             @ */ /* BEGIN_CASE */ void UT_TLS_CERT_CM_SetDefaultPasswordCbUserdata_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; HITLS_CERT_Store *certStore = HITLS_X509_Adapt_StoreNew(); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetCertStore(NULL, certStore, false) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetCertStore(ctx, certStore, false), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetCertStore(ctx) == certStore); ASSERT_TRUE(HITLS_GetCertStore(NULL) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CERT_SetGetAndCheckPrivateKey_API_TC001 * @title The error input parameter for HITLS_SetPrivateKey * @precon nan * @brief 1.Invoke the HITLS_SetPrivateKey interface. Ensure that ctx is empty and privatekey is not empty. * Perform deep copy. Expected result 1 *         2.Invoke the HITLS_SetPrivateKey interface. Ensure that ctx is not empty and privatekey is not empty. * In shallow copy mode, expected result 2 *         3.Invoke the HITLS_GetPrivateKey interface. If ctx is empty, expected result 3 *         4.Invoke the HITLS_CheckPrivateKey interface. If ctx is empty, expected result 1 is obtained * @expect 1.Back HITLS_NULL_INPUT *         2.Back HITLS_SUCCESS * 3.Back HITLS_NULL_INPUT @ */ /* BEGIN_CASE */ void UT_TLS_CERT_SetGetAndCheckPrivateKey_API_TC001(int version, char *keyFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_Key *privatekey = HITLS_X509_Adapt_ProviderKeyParse(tlsConfig, (const uint8_t *)keyFile, sizeof(keyFile), TLS_PARSE_TYPE_FILE, "ASN1", NULL); #else HITLS_CERT_Key *privatekey = HITLS_X509_Adapt_KeyParse(tlsConfig, (const uint8_t *)keyFile, sizeof(keyFile), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); #endif tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetPrivateKey(NULL, privatekey, true) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetPrivateKey(ctx, privatekey, false) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetPrivateKey(NULL) == NULL); ASSERT_TRUE(HITLS_GetPrivateKey(ctx) != NULL); ASSERT_TRUE(HITLS_CheckPrivateKey(NULL) == HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_HITLS_CERT_ClearChainCerts_API_TC001 * @title HITLS_ClearChainCerts interface input parameter test * @precon nan * @brief 1. Invoke HITLS_ClearChainCerts interface. Input empty ctx. Expected result 1 * 2. Invoke HITLS_ClearChainCerts interface. Input non-empty ctx. Expected result 2 * 3. Invoke HITLS_ClearChainCerts interface. Input non-empty ctx and empty tlsConfig->certMgrCtx, * Expected result 1 * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_HITLS_CERT_ClearChainCerts_API_TC001(int version, char *certFile, char *addCertFile) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; HITLS_CERT_X509 *cert = HiTLS_X509_LoadCertFile(tlsConfig, certFile); ASSERT_TRUE(cert != NULL); HITLS_CERT_X509 *addCert = HiTLS_X509_LoadCertFile(tlsConfig, addCertFile); ASSERT_TRUE(addCert != NULL); tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ASSERT_TRUE(HITLS_CFG_SetCertificate(tlsConfig, cert, false) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddChainCert(tlsConfig, addCert, false) == HITLS_SUCCESS); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_ClearChainCerts(NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_ClearChainCerts(ctx) == HITLS_SUCCESS); SAL_CERT_MgrCtxFree(ctx->config.tlsConfig.certMgrCtx); ctx->config.tlsConfig.certMgrCtx = NULL; ASSERT_EQ(HITLS_ClearChainCerts(ctx), HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_sdv_frame_cert_interface_2.c
C
unknown
11,572
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdlib.h> #include <unistd.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_log.h" #include "bsl_err.h" #include "bsl_uio.h" #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_crypt_reg.h" #include "hitls_config.h" #include "tls_config.h" #include "hitls.h" #include "hs_common.h" #include "hitls_func.h" #include "tls.h" #include "conn_init.h" #include "crypt_errno.h" #include "stub_replace.h" #include "frame_tls.h" #include "frame_link.h" #include "rec_wrapper.h" #include "hlt_type.h" #include "hlt.h" #include "process.h" #include "hitls_crypt_init.h" #include "bsl_list.h" #include "simulate_io.h" #include "alert.h" #include "crypt_default.h" #include "stub_crypt.h" #include "hitls_crypt.h" #define READ_BUF_SIZE 18432 #define MAX_CERT_LIST 4294967295 #define MIN_CERT_LIST 0 #define DEFAULT_SECURITYLEVEL 0 /* END_HEADER */ static HITLS_Config *GetHitlsConfigViaVersion(int ver) { HITLS_Config *config; int32_t ret; switch (ver) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); ret = HITLS_CFG_SetCheckKeyUsage(config, false); if (ret != HITLS_SUCCESS) { return NULL; } return config; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); ret = HITLS_CFG_SetCheckKeyUsage(config, false); if (ret != HITLS_SUCCESS) { return NULL; } return config; case HITLS_VERSION_DTLS12: config = HITLS_CFG_NewDTLS12Config(); ret = HITLS_CFG_SetCheckKeyUsage(config, false); if (ret != HITLS_SUCCESS) { return NULL; } return config; default: return NULL; } } typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; bool isSupportRenegotiation; bool isSupportSessionTicket; bool needStopBeforeRecvCCS; } HandshakeTestInfo; static uint8_t g_clientRandom[RANDOM_SIZE]; static uint8_t g_serverRandom[RANDOM_SIZE]; /* @ * @test UT_TLS_CM_SET_GET_UIO_API_TC001 * @title Test the HITLS_SetUio and HITLS_GetUio interfaces * @precon nan * @brief HITLS_SetUio * 1. Input an empty connection context and a non-empty UIO. Expected result 1 is obtained * 2. Input an empty connection context and an empty UIO. Expected result 1 is obtained * 3. Input a non-empty connection context and an empty UIO. Expected result 1 is obtained * 4. Input a non-empty connection context and a non-empty UIO. Expected result 2 is obtained * HITLS_GetUio * 1. Input an empty connection context. Expected result 3 is obtained * 2. Input a non-empty connection context. Expected result 4 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS * 3. Return a null pointer * 4. Return connection uio @*/ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_UIO_API_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx* ctx = HITLS_New(tlsConfig); BSL_UIO *uio = NULL; BSL_UIO *uio2; int32_t ret; uio = BSL_UIO_New(BSL_UIO_TcpMethod()); ret = HITLS_SetUio(NULL, uio); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetUio(NULL, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetUio(ctx, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetUio(ctx, uio); ASSERT_TRUE(ret == HITLS_SUCCESS); uio2 = HITLS_GetUio(NULL); ASSERT_TRUE(uio2 == NULL); uio2 = HITLS_GetUio(ctx); ASSERT_TRUE(uio2 != NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); BSL_UIO_Free(uio); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_GET_READ_UIO_API_TC001 * @title Test the HITLS_SetReadUio, HITLS_GetReadUio interfaces * @precon nan * @brief HITLS_SetReadUio * 1. Input an empty connection context and a non-empty UIO. Expected result 1 is obtained * 2. Input an empty connection context and an empty UIO. Expected result 1 is obtained * 2. Input a non-empty connection context and an empty UIO. Expected result 1 is obtained * 4. Input a non-empty connection context and a non-empty UIO. Expected result 2 is obtained * HITLS_GetReadUio * 1. Input an empty connection context. Expected result 3 is obtained * 2. Input a non-empty connection context. Expected result 4 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS * 3. Return a null pointer * 4. Return connection uio @*/ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_READ_UIO_API_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL) ; HITLS_Ctx* ctx = HITLS_New(tlsConfig); BSL_UIO *uio = NULL; BSL_UIO *uio2 = NULL; int32_t ret; uio = BSL_UIO_New(BSL_UIO_TcpMethod()); ret = HITLS_SetReadUio(NULL, uio); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetReadUio(NULL, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetReadUio(ctx, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetReadUio(ctx, uio); ASSERT_TRUE(ret == HITLS_SUCCESS); uio2 = HITLS_GetReadUio(NULL); ASSERT_TRUE(uio2 == NULL); uio2 = HITLS_GetReadUio(ctx); ASSERT_TRUE(uio2 != NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); BSL_UIO_Free(uio); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_ENDPOINT_FUNC_TC001 * @title Invoke HITLS_SetEndPoint after initialization, check whether the state is handshaking * @precon nan * @brief 1. Initialize the client and server. Expected result 1 is obtained * 2. After initialization, call HITLS_SetEndPoint and check the state status. Expected result 2 is obtained * @expect 1. Complete initialization * 2. state is handshaking @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_ENDPOINT_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); uint32_t ret = HITLS_SetEndPoint(server->ssl, true); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(server->ssl->state, CM_STATE_HANDSHAKING); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test The HITLS_SetEndPoint function fails to be invoked during link establishment * @title UT_TLS_CM_SET_ENDPOINT_FUNC_TC002 * @precon nan * @brief 1. Initialize the client and server. Expected result 1 is obtained * 2. Invoke HITLS_SetEndPoint during link establishment. Expected result 2 is obtained * @expect 1. Complete initialization * 2. Invoking failed @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_ENDPOINT_FUNC_TC002(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_HELLO) == HITLS_SUCCESS); uint32_t ret = HITLS_SetEndPoint(server->ssl, true); ASSERT_EQ(ret, HITLS_MSG_HANDLE_STATE_ILLEGAL); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test Obtains the maximum writable plaintext length after initialization * @title UT_TLS_CM_GET_MAXWRITESIZE_FUNC_TC001 * @precon nan * @brief 1. Initialize the client and server. Expected result 1 is obtained * 2. Invoke HITLS_GetMaxWriteSize to obtain the maximum writable plaintext length. * Expected result 2 is obtained * @expect 1. Complete initialization * 2. Obtain the length successfully, the length is equal to REC_MAX_PLAIN_LENGTH @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_MAXWRITESIZE_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); uint32_t len = 0; uint32_t ret = CONN_Init(client->ssl); ASSERT_EQ(ret, HITLS_SUCCESS); ret = HITLS_GetMaxWriteSize(client->ssl, &len); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(len, REC_MAX_PLAIN_LENGTH); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_GET_USR_DATA_TC001 * @title test HITLS_SetUserData, HITLS_GetUserData interfaces * @precon nan * @brief HITLS_SetUserData * 1. Input an empty connection context and a non-empty userData. Expected result 1 is obtained * 2. Input an empty connection context and an empty userData. Expected result 1 is obtained * 3. Input a non-empty connection context and an empty userData. Expected result 2 is obtained * 4. Input a non-empty connection context and a non-empty userData. Expected result 2 is obtained * HITLS_GetUserData * 1. Input an empty connection context. Expected result 4 is obtained * 2. Input a non-empty connection context. Expected result 3 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS * 3. Return userData * 4. Return a null pointer @*/ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_USR_DATA_API_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL) ; HITLS_Ctx *ctx = HITLS_New(tlsConfig); int32_t ret; uint8_t userData[5] = {0}; void *ret2 = HITLS_GetUserData(NULL); ASSERT_TRUE(ret2 == NULL); ret = HITLS_SetUserData(NULL, &userData); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetUserData(NULL, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetUserData(ctx, NULL); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_SetUserData(ctx, &userData); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_SetUserData(ctx, "userdata"); ASSERT_TRUE(ret == HITLS_SUCCESS); ret2 = HITLS_GetUserData(ctx); ASSERT_TRUE(strcmp(ret2, "userdata") == 0); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_GET_USR_DATA_TC001 * @title test HITLS_SESS_SetUserData, HITLS_SESS_GetUserData interfaces * @precon nan * @brief HITLS_SESS_GetUserData * 1. Input an empty connection context and a non-empty userData. Expected result 1 is obtained * 2. Input an empty connection context and an empty userData. Expected result 1 is obtained * 3. Input a non-empty connection context and an empty userData. Expected result 2 is obtained * 4. Input a non-empty connection context and a non-empty userData. Expected result 2 is obtained * HITLS_SESS_GetUserData * 1. Input an empty connection context. Expected result 4 is obtained * 2. Input a non-empty connection context. Expected result 3 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS * 3. Return userData * 4. Return a null pointer @*/ /* BEGIN_CASE */ void UT_TLS_CM_SESSION_SET_GET_USR_DATA_API_TC001(void) { HitlsInit(); HITLS_Session *session = HITLS_SESS_New(); int32_t ret; uint8_t userData[5] = {0}; void *ret2 = HITLS_SESS_GetUserData(NULL); ASSERT_TRUE(ret2 == NULL); ret = HITLS_SESS_SetUserData(NULL, &userData); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SESS_SetUserData(NULL, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SESS_SetUserData(session, NULL); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_SESS_SetUserData(session, &userData); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_SESS_SetUserData(session, "userdata"); ASSERT_TRUE(ret == HITLS_SUCCESS); ret2 = HITLS_SESS_GetUserData(session); ASSERT_TRUE(strcmp(ret2, "userdata") == 0); EXIT: HITLS_SESS_Free(session); } /* END_CASE */ /* @ * @test HITLS_SetShutdownState Set HITLS_SENT_SHUTDOWN to 1 and do not send the close_notify message. * @title UT_TLS_CM_SET_SHUTDOWN_FUNC_TC001 * @precon nan * @brief 1. Set HITLS_SENT_SHUTDOWN to 1 and invoke the Hitls_Close interface. Expected result 1 is obtained * @expect 1. The interface is successfully invoked and the close_notify message is not sent @*/ /* BEGIN_CASE */ void UT_TLS_CM_SET_SHUTDOWN_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetShutdownState(client->ssl, 1) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Close(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_CLOSED); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); FrameUioUserData *ioUserData = BSL_UIO_GetUserData(server->io); uint32_t readLen = ioUserData->recMsg.len; ASSERT_TRUE(readLen == 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_SHUTDOWN_FUNC_TC001 * @title Use HITLS_GetShutdownState to obtain the configured value * @precon nan * @brief 1. Set HITLS_SENT_SHUTDOWN to 1 and invoke the HITLS_GetShutdownState interface. Expected result 1 * 2. Set HITLS_SENT_SHUTDOWN to 2 and invoke the HITLS_GetShutdownState interface. Expected result 2 * 3. Set HITLS_SENT_SHUTDOWN to 0 and invoke the HITLS_GetShutdownState interface. Expected result 3 * @expect 1. Obtain value 1 * 2. Obtain value 2 * 3. Obtain value 0. * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_SHUTDOWN_FUNC_TC001(int version) { int32_t ret; uint32_t mode; HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(version); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); CONN_Init(ctx); ASSERT_TRUE(ctx != NULL); for (uint32_t i = 0; i <= 2; i++) { ret = HITLS_SetShutdownState(ctx, i); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_GetShutdownState(ctx, &mode); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(mode == i); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_NEGOTIATED_VERSION_FUNC_TC001 * @title HITLS_GetNegotiatedVersion Interface in TLS1.2 Scenario and TLS1.3 Scenario * @precon nan * @brief 1. Set the protocol version to TLS1.2 or TLS1.3. After initialization, invoke the HITLS_GetNegotiatedVersion * interface to obtain the negotiated version number. Expected result 1 is obtained * 2. Set the protocol version to TLS1.2 or TLS1.3. After the connection is established, invoke the * HITLS_GetNegotiatedVersion interface to obtain the negotiated version number. Expected result 2 is obtained * @expect 1. obtained value is 0 * 2. obtained value is tls1.2/tls1.3 @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_NEGOTIATED_VERSION_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); uint16_t negoVersion = HITLS_VERSION_TLCP_DTLCP11; ret = HITLS_GetNegotiatedVersion(client->ssl, &negoVersion); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(negoVersion, 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ret = HITLS_GetNegotiatedVersion(client->ssl, &negoVersion); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(negoVersion, version); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_GET_MAX_PROTO_VERSION_API_TC001 * @title test HITLS_SetMaxProtoVersion, HITLS_GetMaxProtoVersion interfaces * @precon nan * @brief HITLS_SetMaxProtoVersion * 1. Input an empty connection context. Expected result 1 is obtained * 2. Input a non-empty connection context and version is too low. Expected result 2 is obtained * 3. Input a non-empty connection context and normal version. Expected result 3 is obtained * HITLS_GetMaxProtoVersion * 1. Input an empty connection context and a null pointer. Expected result 1 is obtained * 2. Input an empty connection context and a non-empty pointer. Expected result 1 is obtained * 3. Input a non-empty connection context and a non-empty pointer. Expected result 3 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_CONFIG_INVALID_VERSION 3. Return HITLS_SUCCESS @*/ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_MAX_PROTO_VERSION_API_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); int32_t ret; uint16_t maxVersion = 0; ret = HITLS_SetMaxProtoVersion(NULL, HITLS_VERSION_TLS10); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetMaxProtoVersion(ctx, HITLS_VERSION_TLS10); ASSERT_TRUE(ret == HITLS_CONFIG_INVALID_VERSION); ret = HITLS_SetMaxProtoVersion(ctx, HITLS_VERSION_TLS13); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_GetMaxProtoVersion(NULL, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_GetMaxProtoVersion(NULL, &maxVersion); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_GetMaxProtoVersion(ctx, &maxVersion); ASSERT_TRUE(ret == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_GET_MIN_PROTO_VERSION_API_TC001 * @title test HITLS_SetMinProtoVersion, HITLS_GetMinProtoVersion interfaces * @precon nan * @brief HITLS_SetMaxProtoVersion * 1. Input an empty connection context. Expected result 1 is obtained * 2. Input a non-empty connection context and version is too high. Expected result 2 is obtained * 3. Input a non-empty connection context and normal version. Expected result 3 is obtained * HITLS_GetMinProtoVersion * 1. Input an empty connection context and a null pointer. Expected result 1 is obtained * 2. Input an empty connection context and a non-empty pointer. Expected result 1 is obtained * 3. Input a non-empty connection context and a non-empty pointer. Expected result 3 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_CONFIG_INVALID_VERSION * 3. Return HITLS_SUCCESS @*/ /* BEGIN_CASE */ void UT_TLS_CM_SET_GET_MIN_PROTO_VERSION_API_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL) ; HITLS_Ctx *ctx = HITLS_New(tlsConfig); int32_t ret; uint16_t minVersion = 0; ret = HITLS_SetMinProtoVersion(NULL, HITLS_VERSION_TLS12); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetMinProtoVersion(ctx, HITLS_VERSION_TLS13); ASSERT_TRUE(ret == HITLS_CONFIG_INVALID_VERSION); ret = HITLS_SetMinProtoVersion(ctx, HITLS_VERSION_TLS12); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_GetMinProtoVersion(NULL, NULL); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_GetMinProtoVersion(NULL, &minVersion); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_GetMinProtoVersion(ctx, &minVersion); ASSERT_TRUE(ret == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_IS_AEAD_FUNC_TC001 * @title HITLS_IsAead Obtains whether to use the AEAD algorithm after negotiation * @precon TLS12, HITLS_RSA_with_AES_128_CBC_SHA256 (not AEAD), TLS13, HITLS_CHACHA20_POLY1305_SHA256 / * HITLS_AES_128_GCM_SHA256 (AEAD) * @brief 1. Initialize the client and server and set the cipherSuite. Expected result 1 * 2. After connection is established, invoke HITLS_IsAead to check whether * the AEAD algorithm is negotiated. Expected result 2 * @expect 1. Initialization is complete. * 2. Value of isAEAD @ */ /* BEGIN_CASE */ void UT_TLS_CM_IS_AEAD_FUNC_TC001(int version, int ciphersuite) { FRAME_Init(); int ret; uint8_t isAEAD = 0; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t cipherSuites[] = {(uint16_t)ciphersuite}; HITLS_CFG_SetCipherSuites(config_c, cipherSuites, sizeof(cipherSuites) / sizeof(uint16_t)); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ret = HITLS_IsAead(client->ssl, &isAEAD); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(isAEAD == (version == HITLS_VERSION_TLS13)); ret = HITLS_IsAead(server->ssl, &isAEAD); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(isAEAD == (version == HITLS_VERSION_TLS13)); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test HITLS_IsHandShakeDone Check whether the handshake is complete during connection establishment * @title UT_TLS_CM_IS_HSDONE_FUNC_TC001 * @precon nan * @brief 1. Initialize the client and server. Expected result 1 * 2. During connection establishment, invoke HITLS_IsHandShakeDone to check whether the handshake is complete. * Expected result 2 * @expect 1. Initialization is complete * 2. The interface returns 0 and the handshake is not done @ */ /* BEGIN_CASE */ void UT_TLS_CM_IS_HSDONE_FUNC_TC001(int version, int state) { FRAME_Init(); int ret; uint8_t isDone; HITLS_Config *config = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_HandshakeState curState = (HITLS_HandshakeState)state; ret = FRAME_CreateConnection(client, server, true, curState); ret = HITLS_IsHandShakeDone(client->ssl, &isDone); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(isDone == 0); ret = HITLS_IsHandShakeDone(server->ssl, &isDone); ASSERT_TRUE(ret == HITLS_SUCCESS); if (version == HITLS_VERSION_TLS12 && curState == TRY_RECV_FINISH) { ASSERT_TRUE(isDone == 1); } else { ASSERT_TRUE(isDone == 0); } EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test HITLS_IsHandShakeDone Check whether the handshake is complete after connection establishment * @title UT_TLS_CM_IS_HSDONE_FUNC_TC002 * @precon nan * @brief 1. Initialize the client and server. Expected result 1 * 2. After the connection is established, invoke HITLS_IsHandShakeDone to check whether the handshake * is complete. Expected result 2 * @expect 1. Initialization is complete * 2. The interface returns 1 and the handshake is done @ */ /* BEGIN_CASE */ void UT_TLS_CM_IS_HSDONE_FUNC_TC002(int version) { FRAME_Init(); int ret; uint8_t isDone; HITLS_Config *config = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ret = HITLS_IsHandShakeDone(client->ssl, &isDone); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(isDone == 1); ret = HITLS_IsHandShakeDone(server->ssl, &isDone); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(isDone == 1); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_IS_SERVER_FUNC_TC001 * @title HITLS_IsServer The client invokes the interface to determine whether the current server is the server * @precon nan * @brief 1. Initialize the client and server. Expected result 1 * 2. The client invokes the HITLS_IsServer interface to determine whether the current client is a server. * Expected result 2 * 3. The server invokes the HITLS_IsServer interface to determine whether the current server is a server. * Expected result 3 * @expect 1. Initialization is complete * 2. The interface returns false * 3. The interface returns true @ */ /* BEGIN_CASE */ void UT_TLS_CM_IS_SERVER_FUNC_TC001(int version) { FRAME_Init(); int ret; uint8_t isServer; HITLS_Config *config = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ret = HITLS_IsServer(client->ssl, &isServer); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(isServer == false); ret = HITLS_IsServer(server->ssl, &isServer); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(isServer == true); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_READHASPENDING_FUNC_TC001 * @title HITLS_ReadHasPending Interface test * @precon nan * @brief 1. After initialization, invoke the hitls_readhaspending interface. Expected result 1 is obtained. * 2. After the connection is established, the peer sends data and the local * invokes the hitls_readhaspending interface. Expected result 2 is obtained. * @expect 1. Return 0 * 2. Return 1 @ */ /* BEGIN_CASE */ void UT_TLS_CM_READHASPENDING_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; uint8_t isPending = 0; ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_ReadHasPending(client->ssl, &isPending) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_ReadHasPending(server->ssl, &isPending) == HITLS_SUCCESS); ASSERT_EQ(isPending, 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_TRUE(HITLS_Write(client->ssl, data, sizeof(data), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(client, server) == HITLS_SUCCESS); uint8_t readBuf[5] = {0}; uint32_t readLen = 0; ASSERT_TRUE(HITLS_Read(server->ssl, readBuf, 5, &readLen) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_ReadHasPending(server->ssl, &isPending) == HITLS_SUCCESS); ASSERT_EQ(isPending, 1); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_READPENDING_FUNC_TC001 * @title HITLS_GetReadPendingBytes interfaces test * @precon nan * @brief 1. After initialization, invoke the HITLS_GetReadPendingBytes interface to query data. * Expected result 1 is obtained. * 2. Simulate a scenario where the peer end sends app data during renegotiation to generate app data cache, * and invoke HITLS_GetReadPendingBytes to obtain the cache value. Expected result 2 is obtained. * 3. When the buffer length of the HITLS_Read read data is less than 16 KB, some data is left. * Invoke the HITLS_GetReadPendingBytes interface to query the data. Expected result 3 is obtained. * @expect 1. The return value is 0. * 2. Returns the size of the cached value. * 3. Returns the size of the left value. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_READPENDING_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_GetReadPendingBytes(server->ssl) == 0); ASSERT_TRUE(HITLS_GetReadPendingBytes(client->ssl) == 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(client->ssl) == HITLS_SUCCESS); uint8_t data[] = "Hello World"; uint32_t writeLen; ASSERT_TRUE(HITLS_Write(server->ssl, data, sizeof(data), &writeLen) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Connect(client->ssl) == HITLS_REC_NORMAL_IO_BUSY); client->ssl->state = CM_STATE_ALERTING; ASSERT_TRUE(HITLS_GetReadPendingBytes(client->ssl) == sizeof("Hello World")); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test HITLS_GetPeerSignScheme Unidirectional authentication on the client * @title UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC001 * @precon nan * @brief 1. Configure unidirectional authentication. After the negotiation is complete, * call the interface to obtain the local signature hash algorithm. Expected result 1 is displayed. * 2. Call the interface to obtain the peer signature hash algorithm. Expected result 2 is obtained. * @expect 1. Return 0 * 2. Return 0 @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, false); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); HITLS_SignHashAlgo peerSignScheme = CERT_SIG_SCHEME_UNKNOWN; uint32_t ret = HITLS_GetPeerSignScheme(server->ssl, &peerSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(peerSignScheme, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test HITLS_GetPeerSignScheme Client two-way authentication Verification * @title UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC002 * @precon nan * @brief 1. Set two-way authentication. Before the client receives the certificate request, call the interface to * obtain the local signature hash algorithm. Expected result 1 is obtained. * 2. After receiving the certificate request, the client invokes the interface to obtain the negotiated 8 signature hash algorithm. Expected result 2 is displayed. * @expect 1. Return 0 * 2. The returned value is the negotiated algorithm @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC002(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, true); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_CERTIFICATE_REQUEST) == HITLS_SUCCESS); HITLS_SignHashAlgo peerSignScheme = CERT_SIG_SCHEME_UNKNOWN; // uint32_t ret = HITLS_GetPeerSignScheme(client->ssl, &peerSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); if (version == HITLS_VERSION_TLS13) { ASSERT_EQ(peerSignScheme, 0); } else { ASSERT_NE(peerSignScheme, 0); } ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); peerSignScheme = CERT_SIG_SCHEME_UNKNOWN; ret = HITLS_GetPeerSignScheme(client->ssl, &peerSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_NE(peerSignScheme, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC003 * @title HITLS_GetPeerSignScheme Client Verification * @precon nan * @brief 1. Before the client receives the serverkeyexchange message, call the interface to obtain the peer signature * hash algorithm. Expected result 1 is displayed. * 2. After receiving the serverkeyexchange message, the client invokes the interface to obtain the signature * hash algorithm of the peer end. Expected result 2 is obtained. * @expect 1. Return 0 * 2. The return value is the algorithm used by the server @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC003(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); HITLS_CFG_SetClientVerifySupport(config, true); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_SignHashAlgo peerSignScheme = CERT_SIG_SCHEME_UNKNOWN; uint32_t ret = HITLS_GetPeerSignScheme(server->ssl, &peerSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(peerSignScheme, 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); peerSignScheme = CERT_SIG_SCHEME_UNKNOWN; ret = HITLS_GetPeerSignScheme(client->ssl, &peerSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(peerSignScheme, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC004 * @title HITLS_GetPeerSignScheme two-way authentication verification on the server * @precon nan * @brief 1. Set two-way authentication. Before the server receives the certificate verify message, * call the API to obtain the peer signature hash algorithm. Expected result 1 is obtained. * 2. After receiving the certificate verify message, the server invokes the API to obtain the signature hash * algorithm of the peer end. Expected result 2 is obtained. * @expect 1. Return 0 * 2. The returned value is the algorithm used by the client @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_PEER_SIGN_SCHEME_FUNC_TC004(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); HITLS_CFG_SetClientVerifySupport(config, true); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_SEND_CERTIFICATE_VERIFY) == HITLS_SUCCESS); HITLS_SignHashAlgo peerSignScheme = CERT_SIG_SCHEME_UNKNOWN; uint32_t ret = HITLS_GetPeerSignScheme(server->ssl, &peerSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(peerSignScheme, 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); peerSignScheme = CERT_SIG_SCHEME_UNKNOWN; ret = HITLS_GetPeerSignScheme(server->ssl, &peerSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_NE(peerSignScheme, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_LOCAL_SIGN_SCHEME_FUNC_TC001 * @title HITLS_GetLocalSignScheme Server-side verification * @precon nan * @brief 1. Before the server receives the client hello message, call the interface to obtain the negotiated signature * hash algorithm. Expected result 1 is displayed * 2. After receiving the client hello message, the server invokes the interface to obtain the negotiated * signature hash algorithm. Expected result 2 is displayed * @expect 1. Return 0 * 2. The return value is the algorithm used by the server @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_LOCAL_SIGN_SCHEME_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_SignHashAlgo localSignScheme = CERT_SIG_SCHEME_UNKNOWN; ret = HITLS_GetLocalSignScheme(server->ssl, &localSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(localSignScheme, 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ret = HITLS_GetLocalSignScheme(server->ssl, &localSignScheme); ASSERT_EQ(ret, HITLS_SUCCESS); switch (version) { case HITLS_VERSION_TLS12: ASSERT_EQ(localSignScheme, CERT_SIG_SCHEME_RSA_PKCS1_SHA256); break; case HITLS_VERSION_TLS13: ASSERT_EQ(localSignScheme, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256); break; default: config = NULL; break; } EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_EC_GROUPS_FUNC_TC001 * @title test HITLS_SetEcGroups interface * @precon nan * @brief 1. Input an empty link context and a non-empty group. Normal groupsize. Expected result 1 is obtained * 2. Input a non-empty link context, empty group, and normal groupsize. Expected result 1 is obtained. * 3. Input a non-empty link context, a non-empty group, and groupsize 0. Expected result 1 is obtained * 4. Transfer a non-empty link context, a non-empty group, and normal groupsize. Expected result 2 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_EC_GROUPS_FUNC_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); uint16_t groups[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP521R1}; uint32_t groupsSize = sizeof(groups) / sizeof(uint16_t); int32_t ret; ret = HITLS_SetEcGroups(NULL, groups, groupsSize); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetEcGroups(ctx, NULL, groupsSize); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetEcGroups(ctx, groups, 0); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetEcGroups(ctx, groups, groupsSize); ASSERT_TRUE(ret == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_SIGAL_LIST_FUNC_TC001 * @title test HITLS_SetSigalgsList interface * @precon nan * @brief 1. Input an empty link context and a non-empty signAlg. Normal signAlgsSize. Expected result 1 is obtained * 2. Input an non-empty link context and an empty signAlg. Normal signAlgsSize. Expected result 1 is obtained * 2. Input a non-empty link context and a non-empty signAlg. 0 signAlgsSize. Expected result 1 is obtained * 2. Input a non-empty link context and a non-empty signAlg. Normal signAlgsSize. Expected result 2 is obtained * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS @*/ /* BEGIN_CASE */ void UT_TLS_CM_SET_SIGAL_LIST_FUNC_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL) ; HITLS_Ctx *ctx = HITLS_New(tlsConfig); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; uint32_t signAlgsSize = sizeof(signAlgs) / sizeof(uint16_t); int32_t ret; ret = HITLS_SetSigalgsList(NULL, signAlgs, signAlgsSize); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetSigalgsList(ctx, NULL, signAlgsSize); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetSigalgsList(ctx, signAlgs, 0); ASSERT_TRUE(ret == HITLS_NULL_INPUT); ret = HITLS_SetSigalgsList(ctx, signAlgs, signAlgsSize); ASSERT_TRUE(ret == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_EC_POINT_FUNC_TC001 * @title Set the normal dot format value. * @precon nan * @brief 1. Set pointFormats to HITLS_POINT_FORMAT_UNCOMPRESSED and invoke the HITLS_CFG_SetEcPointFormats interface. * Expected result 1 is obtained. * 2. Set pointFormats to HITLS_POINT_FORMAT_BUTT and invoke the HITLS_CFG_SetEcPointFormats interface. * Expected result 2 * 3. Use config to generate ctx, due to the result 3 * 4. Set pointFormats to HITLS_POINT_FORMAT_UNCOMPRESSED again and generate ctx again. Expected result 4 is * obtained. Set pointFormats to HITLS_POINT_FORMAT_UNCOMPRESSED and invoke the HITLS_SetEcPointFormats * interface. Expected result 2 * @expect 1. Interface return value, HITLS_SUCCESS * 2. Interface return value: HITLS_SUCCESS * 3. Failed to generate the file. * 4. The file is generated successfully. * 5. The setting is successful. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_EC_POINT_FUNC_TC001(int version) { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *Config = NULL; HITLS_Ctx *ctx = NULL; Config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(Config != NULL); const uint8_t pointFormats[] = {HITLS_POINT_FORMAT_UNCOMPRESSED}; uint32_t pointFormatsSize = sizeof(pointFormats) / sizeof(uint8_t); ASSERT_TRUE(HITLS_CFG_SetEcPointFormats(Config, pointFormats, pointFormatsSize) == HITLS_SUCCESS); const uint8_t pointFormats2[] = {HITLS_POINT_FORMAT_BUTT}; uint32_t pointFormatsSize2 = sizeof(pointFormats2) / sizeof(uint8_t); ASSERT_TRUE(HITLS_CFG_SetEcPointFormats(Config, pointFormats2, pointFormatsSize2) == HITLS_SUCCESS); ctx = HITLS_New(Config); if(version == TLS1_2){ ASSERT_TRUE(ctx == NULL); } HITLS_Free(ctx); ASSERT_TRUE(HITLS_CFG_SetEcPointFormats(Config, pointFormats, pointFormatsSize) == HITLS_SUCCESS); ctx = HITLS_New(Config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetEcPointFormats(ctx, pointFormats, pointFormatsSize) == HITLS_SUCCESS); client = FRAME_CreateLink(Config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(Config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(Config); HITLS_Free(ctx); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_CONFIG_FUNC_TC001 * @title After the initialization is complete, obtain the config file and check whether the configuration is consistent * @precon nan * @brief 1. Initialize the client and server. Expected result 1 is obtained * 2. After the initialization is complete, obtain hitlsConfig and check whether the main configurations are * consistent with the settings. Expected result 2 is obtained. * @expect 1. Complete initialization * 2. Consistent results @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_CONFIG_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); const HITLS_Config *cfgFromCtx = NULL; cfgFromCtx = HITLS_GetConfig(client->ssl); ASSERT_TRUE(cfgFromCtx != NULL); ASSERT_EQ(cfgFromCtx->signAlgorithmsSize, sizeof(signAlgs) / sizeof(uint16_t)); ASSERT_TRUE(memcmp(cfgFromCtx->signAlgorithms, signAlgs, cfgFromCtx->signAlgorithmsSize) == 0); ASSERT_EQ(cfgFromCtx->isSupportRenegotiation, true); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_CURRENT_CIPHER_FUNC_TC001 * @title HITLS_GetCurrentCipher Obtain the negotiated cipher suite pointer after initialization and before negotiation * @precon nan * @brief 1. Initialize the client and server. Expected result 1 is obtained * 2. Before link establishment, call HITLS_GetCurrentCipher to obtain the negotiated cipher suite pointer. * Expected result 2 is returned. * @expect 1. Complete initialization * 2. Return NULL @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_CURRENT_CIPHER_FUNC_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; tlsConfig = GetHitlsConfigViaVersion(version); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); CONN_Init(ctx); ASSERT_TRUE(ctx != NULL); const HITLS_Cipher *hitlsCipher = HITLS_GetCurrentCipher(ctx); ASSERT_EQ(hitlsCipher->cipherSuite, 0); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_GET_RANDOM_FUNC_TC001 * @title tls1.3 Obtain clientRandom and serverRandom * @precon nan * @brief 1. establish connection * 2. Obtain and compare clientRandom and serverRandom. * @expect 1. Return success * 2. The clientRandom stored on the server is the same as that sent by the client, and the serverRandom stored 8 on the client is the same as that sent by the server. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_RANDOM_FUNC_TC001(void) { HandshakeTestInfo testInfo = {0}; FRAME_Init(); testInfo.config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(testInfo.config != NULL); testInfo.client = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLink(testInfo.config, BSL_UIO_TCP); ASSERT_TRUE(testInfo.server != NULL); FRAME_CreateConnection(testInfo.client, testInfo.server, true, HS_STATE_BUTT); uint8_t clientRandom[RANDOM_SIZE]; uint8_t serverRandom[RANDOM_SIZE]; uint32_t randomSize = RANDOM_SIZE; ASSERT_TRUE(HITLS_GetHsRandom(testInfo.client->ssl, g_clientRandom, &randomSize, true) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetHsRandom(testInfo.server->ssl, clientRandom, &randomSize, true) == HITLS_SUCCESS); ASSERT_TRUE(randomSize == RANDOM_SIZE); ASSERT_TRUE(memcmp(g_clientRandom, clientRandom, RANDOM_SIZE) == 0); ASSERT_TRUE(HITLS_GetHsRandom(testInfo.server->ssl, g_serverRandom, &randomSize, false) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetHsRandom(testInfo.client->ssl, serverRandom, &randomSize, false) == HITLS_SUCCESS); ASSERT_TRUE(randomSize == RANDOM_SIZE); ASSERT_TRUE(memcmp(g_serverRandom, serverRandom, RANDOM_SIZE) == 0); EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /* @ * @test HITLS_GetHandShakeState change state to alerting, obtain the state * @title UT_TLS_CM_GET_HANDSHAKE_STATE_FUNC_TC001 * @precon nan * @brief 1. Initialize the client and server. Expected result 1 is obtained * 2. When an alerting message is generated during data transmission, invoke HITLS_GetHandShakeState to stop * sending the alerting message and obtain the current status. Expected result 2 is obtained * @expect 1. Complete initialization * 2. Return TLS_CONNECTED @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_HANDSHAKE_STATE_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); client->ssl->method.sendAlert(client->ssl, ALERT_LEVEL_WARNING, ALERT_NO_CERTIFICATE_RESERVED); ret = ALERT_Flush(client->ssl); ASSERT_EQ(ret, HITLS_SUCCESS); uint32_t state = 0; ret = HITLS_GetHandShakeState(client->ssl, &state); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(state, TLS_CONNECTED); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test HITLS_GetStateString Query the handshake status in sequence. * @title UT_TLS_CM_GET_STATE_STRING_FUNC_TC001 * @precon nan * @brief 1. Invoke the HITLS_GetStateString interface and transfer values 0-30 and 255 at a time. Expected result 1. * @expect 1. The interface returns the corresponding handshake status. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_STATE_STRING_FUNC_TC001() { const char goalStr[34][32] = { "idle", "connected", "send hello request", "send client hello", "send hello retry request", "send server hello", "send hello verify request", "send encrypted extensions", "send certificate", "send server key exchange", "send certificate request", "send server hello done", "send client key exchange", "send certificate verify", "send new session ticket", "send change cipher spec", "send end of early data", "send finished", "send keyupdate", "recv client hello", "recv server hello", "recv hello verify request", "recv encrypted extensions", "recv certificate", "recv server key exchange", "recv certificate request", "recv server hello done", "recv client key exchange", "recv certificate verify", "recv new session ticket", "recv end of early data", "recv finished", "recv keyupdate", "recv hello request", }; int32_t ret; for (uint32_t i = 0; i <= 30; i++) { ret = strcmp(HITLS_GetStateString(i), goalStr[i]); ASSERT_TRUE(strcmp(HITLS_GetStateString(i), goalStr[i]) == 0); } ASSERT_TRUE(strcmp(HITLS_GetStateString(255), "unknown") == 0); EXIT: return; } /* END_CASE */ /* @ * @test HITLS_IsHandShaking function point test * @title UT_TLS_CM_IS_HANDSHAKING_FUNC_TC001 * @precon nan * @brief 1. Initialize the client and server. Expected result 1. * 2. Invoke the HITLS_IsHandShaking interface to check whether handshake is in progress. Expected result 2. * 3. Initiate a connection establishment request and invoke the HITLS_IsHandShaking interface during connection establishment. (Expected result 3) * 4. Invoke HITLS_IsHandShaking to complete connection establishment. Expected result 4. * 5. Invoke the HITLS_Renegotiate interface to initiate renegotiation. (Expected result 5.) * 6. Invoke the HITLS_IsHandShaking interface to check whether the handshake is in progress. (Expected result 6) * 7. After the renegotiation is complete, invoke the HITLS_IsHandShaking interface to check whether handshake is in progress. Expected result 7. *@expect 1. Initialization is complete. * 2. The interface output parameter is 0. * 3. The interface output parameter is 1. * 4. The interface output parameter is 0. * 5. The state changes to the renegotiation state. * 6. The output parameter of the interface is 1. * 7. The interface output parameter is 0. @ */ /* BEGIN_CASE */ void UT_TLS_CM_IS_HANDSHAKING_FUNC_TC001(int version) { FRAME_Init(); uint8_t isHandShaking = 0; HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(version); ASSERT_TRUE(tlsConfig != NULL); tlsConfig->isSupportRenegotiation = true; FRAME_LinkObj *client = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(tlsConfig, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_IDLE); ASSERT_TRUE(HITLS_IsHandShaking(clientTlsCtx, &isHandShaking) == HITLS_SUCCESS); ASSERT_TRUE(isHandShaking == 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(HITLS_IsHandShaking(clientTlsCtx, &isHandShaking) == HITLS_SUCCESS); ASSERT_TRUE(isHandShaking == 1); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_IsHandShaking(clientTlsCtx, &isHandShaking) == HITLS_SUCCESS); ASSERT_TRUE(isHandShaking == 0); if (version == HITLS_VERSION_TLS12) { ASSERT_EQ(HITLS_Renegotiate(clientTlsCtx), HITLS_SUCCESS); ASSERT_EQ(HITLS_Renegotiate(serverTlsCtx), HITLS_SUCCESS); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_RENEGOTIATION); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_RENEGOTIATION); ASSERT_TRUE(HITLS_IsHandShaking(clientTlsCtx, &isHandShaking) == HITLS_SUCCESS); ASSERT_TRUE(isHandShaking == 1); ASSERT_TRUE(FRAME_CreateRenegotiationState(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_IsHandShaking(clientTlsCtx, &isHandShaking) == HITLS_SUCCESS); ASSERT_TRUE(isHandShaking == 0); } EXIT: HITLS_CFG_FreeConfig(tlsConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_CM_HITLS_IsBeforeHandShake_FUNC_TC001 * @title HITLS_IsBeforeHandShake Check whether the handshake is not performed * @percon NA * @brief * 1. Initialize the client and server. Expected result 1 * 2. Call HITLS_IsBeforeHandShake to check whether the handshake has not been performed. Expected result 2 * 3. During transporting, call HITLS_IsBeforeHandShake to check whether the handshake has not been performed * Expected result 3 * 4. Establish a connection and invoke the HITLS_IsBeforeHandShake interface to check whether the handshake * has not been performed.Expected result 4 * @expect * 1. Initialization is complete * 2. isBefore will be 1 * 3. isBefore will be 0 * 4. isBefore will be 0 */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_IsBeforeHandShake_FUNC_TC001(int version) { FRAME_Init(); int ret = 0; uint8_t isBefore = 0; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ret = HITLS_IsBeforeHandShake(client->ssl, &isBefore); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_IDLE); ASSERT_TRUE(isBefore == 1); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); ret = HITLS_IsBeforeHandShake(client->ssl, &isBefore); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_HANDSHAKING); ASSERT_TRUE(isBefore == 0); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(client->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(isBefore == 0); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_CM_HITLS_GetClientVersion_FUNC_TC001 * @title HITLS_GetClientVersion Obtains the client and server version numbers * after initialization and before negotiation. * @percon NA * @brief * 1. Initialize the client and server. Expected result 1 * 2. Call HITLS_GetClientVersion to obtain the client and server version numbers. Expected result 2 * @expect * 1. Completing the initialization * 2. The interface returns all 0s */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetClientVersion_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); uint16_t clientVersion = HITLS_VERSION_TLS12; ASSERT_TRUE(HITLS_GetClientVersion(client->ssl, &clientVersion) == HITLS_SUCCESS); uint16_t serverVersion = HITLS_VERSION_TLS12; ASSERT_TRUE(HITLS_GetClientVersion(server->ssl, &serverVersion) == HITLS_SUCCESS); ASSERT_EQ(clientVersion, 0); ASSERT_EQ(serverVersion, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_CM_HITLS_IsClient_FUNC_TC001 * @title Testing the HITLS_IsClient * @percon NA * @brief * 1. Enter an empty TLS connection handle. Expected result 1 * 2. Enter a non-empty TLS connection handle and leave isClient empty. Expected result 1 * 3. Enter a non-empty TLS connection handle and leave isClient not empty. Expected result 2 * @expect * 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCESS */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_IsClient_FUNC_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool isClient = 0; ASSERT_TRUE(HITLS_IsClient(ctx, &isClient) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_IsClient(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_IsClient(ctx, &isClient) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test HITLS_GetSharedGroup Obtain the first supported peer group when only one curve is matched on the client and server. * @title UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC001 * @precon nan * @brief * 1. Initialize the client and server. Expected result 1 * 2. Configure the client and server to support only one elliptic curve (the number of intersection groups is 1). Expected result 2 * 3. Establish a connection and invoke the HITLS_GetSharedGroup interface to obtain the first supported peer group (Expected result 3) * @expect * 1. Initialization is complete * 2. The setting is successful * 3. The interface returns the supported elliptic curve @ */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC001(int version) { FRAME_Init(); int ret; uint16_t groupId; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t groups_c[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; HITLS_CFG_SetGroups(config_c, groups_c, sizeof(groups_c) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); uint16_t groups_s[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP521R1}; uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512, CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; HITLS_CFG_SetGroups(config_s, groups_s, sizeof(groups_s) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ret = HITLS_GetSharedGroup(server->ssl, 1, &groupId); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(groupId == HITLS_EC_GROUP_SECP256R1); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetSharedGroup Obtain the second supported peer group if only one matching curve exists on the client and * server. * @title UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC002 * @precon nan * @brief * 1. Initialize the client and server. Expected result 1 * 2. Configure only one elliptic curve supported by the client and server. Expected result 2 * 3. Establish a connection and invoke the HITLS_GetSharedGroup interface to obtain the second supported peer group, * Expected result 3 * @expect * 1. Initialization is complete * 2. The setting is successful * 3. The interface returns 0 */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC002(int version) { FRAME_Init(); int ret; uint16_t groupId; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t groups_c[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; HITLS_CFG_SetGroups(config_c, groups_c, sizeof(groups_c) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); uint16_t groups_s[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP521R1}; uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512, CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; HITLS_CFG_SetGroups(config_s, groups_s, sizeof(groups_s) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ret = HITLS_GetSharedGroup(server->ssl, 2, &groupId); ASSERT_TRUE(ret == HITLS_INVALID_INPUT); ASSERT_TRUE(groupId == 0); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetSharedGroup Obtain the second and third supported peer groups when the client and server have two * matching curves. * @title UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC003 * @precon nan * @brief * 1. Initialize the client and server. Expected result 1 * 2. Configure two elliptic curves supported by the client and server. Expected result 2 * 3. Establish a connection. Invoke HITLS_GetSharedGroup to obtain the second supported peer group and the third * supported peer group, Expected result 3 * @expect * 1. Initialization is complete * 2. The setting is successful * 3. The corresponding curve is returned for the first call and 0 is returned for the second call */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC003(int version) { FRAME_Init(); int ret; uint16_t groupId; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t groups_c[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; HITLS_CFG_SetGroups(config_c, groups_c, sizeof(groups_c) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); uint16_t groups_s[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1, HITLS_EC_GROUP_SECP521R1}; uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512}; HITLS_CFG_SetGroups(config_s, groups_s, sizeof(groups_s) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ret = HITLS_GetSharedGroup(server->ssl, 2, &groupId); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(groupId == HITLS_EC_GROUP_SECP384R1); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetSharedGroup Obtain the first supported peer group when there is no matching curve on the client and * server * @title UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC004 * @precon In the current framework, the TLS13 client and server do not have a matching curve. The TLS12 client and * server can successfully establish a connection. The TLS13 framework capability needs to be supplemented * @brief * 1. Initialize the client and server, Expected result 1 * 2. Configure the client and server not to support the elliptic curve. Expected result 2 * 3. Establish a connection. After the parameters are negotiated, invoke the HITLS_GetSharedGroup interface to obtain * the supported peer group. Expected result 3 * @expect * 1. Initialization is complete * 2. The setting is successful * 3. The interface returns 0 */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC004(int version) { FRAME_Init(); int ret; uint16_t groupId; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); uint16_t signWrtVersion = (version == HITLS_VERSION_TLS12) ? CERT_SIG_SCHEME_RSA_PKCS1_SHA256 : CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t groups_c[] = {HITLS_EC_GROUP_SECP384R1}; uint16_t signAlgs_c[] = {signWrtVersion, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384}; HITLS_CFG_SetGroups(config_c, groups_c, sizeof(groups_c) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); HITLS_CFG_SetDhAutoSupport(config_c, true); uint16_t groups_s[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP521R1}; uint16_t signAlgs_s[] = { signWrtVersion, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512}; HITLS_CFG_SetGroups(config_s, groups_s, sizeof(groups_s) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); HITLS_CFG_SetDhAutoSupport(config_s, true); FRAME_CertInfo certInfo = { "rsa_pss_sha256/rsa_pss_root.crt", "rsa_pss_sha256/rsa_pss_intCa.crt", "rsa_pss_sha256/rsa_pss_dev.crt", 0, "rsa_pss_sha256/rsa_pss_dev.key", 0, }; client = (version == HITLS_VERSION_TLS12) ? FRAME_CreateLink(config_c, BSL_UIO_TCP) : FRAME_CreateLinkWithCert(config_c, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); server = (version == HITLS_VERSION_TLS12) ? FRAME_CreateLink(config_s, BSL_UIO_TCP) : FRAME_CreateLinkWithCert(config_s, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(server != NULL); ret = FRAME_CreateConnection(client, server, true, HS_STATE_BUTT); ASSERT_TRUE(ret == HITLS_SUCCESS); ret = HITLS_GetSharedGroup(server->ssl, 1, &groupId); ASSERT_TRUE(ret == HITLS_INVALID_INPUT); ASSERT_TRUE(groupId == 0); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetSharedGroup If the matched elliptic curve exists, obtain the (-1)th supported peer group. * @title UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC005 * @precon nan * @brief * 1. Initialize the client and server. Expected result 1 * 2. Configure two elliptic curves supported by the client and server. Expected result 2 * 3. Establish a connection. Invoke HITLS_GetSharedGroup to obtain the (-1)th supported peer group. Expected result 3 * @expect * 1. Initialization is complete * 2. The setting is successful * 3. The interface returns 2 */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetSharedGroup_FUNC_TC005(int version) { FRAME_Init(); int ret; uint16_t groupId; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t groups_c[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1}; uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, CERT_SIG_SCHEME_RSA_PKCS1_SHA256}; HITLS_CFG_SetGroups(config_c, groups_c, sizeof(groups_c) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); uint16_t groups_s[] = {HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1, HITLS_EC_GROUP_SECP521R1}; uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512}; HITLS_CFG_SetGroups(config_s, groups_s, sizeof(groups_s) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ret = HITLS_GetSharedGroup(server->ssl, -1, &groupId); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(groupId == 2); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_TLS_CM_HITLS_SetVersionSupport_HITLS_GetVersionSupport_API_TC001 * @title Test the HITLS_SetVersionSupport and HITLS_GetVersionSupport interfaces. * @precon nan * @brief * HITLS_SetVersionSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Input a non-empty TLS connection handle and set the version to an invalid value. Expected result 2 * 3. Input a non-empty TLS connection handle and set the version to a valid value. Expected result 3 * HITLS_GetVersionSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Input an empty version pointer. Expected result 1 * 3. Input a non-empty TLS connection handle and ensure that the version pointer is not empty. Expected result 4 * @expect * 1. Return HITLS_NULL_INPUT. * 2. Return HITLS_SUCCESS, and invalid values in ctx->config.tlsConfig are filtered out * 3. Return HITLS_SUCCESS is returned, and the value of ctx->config.tlsConfig is the expected value * 4. Return HITLS_SUCCESS is returned and the value of version is the same as that recorded in config */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_SetVersionSupport_HITLS_GetVersionSupport_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint32_t version = 0; ASSERT_TRUE(HITLS_SetVersionSupport(ctx, version) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetVersionSupport(ctx, &version) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetVersionSupport(ctx, NULL) == HITLS_NULL_INPUT); version = (TLS13_VERSION_BIT << 1) | TLS13_VERSION_BIT | TLS12_VERSION_BIT; ASSERT_TRUE(HITLS_SetVersionSupport(ctx, version) == HITLS_SUCCESS); ASSERT_TRUE(ctx->config.tlsConfig.minVersion == HITLS_VERSION_TLS12 && ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13); version = TLS13_VERSION_BIT | TLS12_VERSION_BIT; ASSERT_TRUE(HITLS_SetVersionSupport(ctx, version) == HITLS_SUCCESS); ASSERT_TRUE(ctx->config.tlsConfig.minVersion == HITLS_VERSION_TLS12 && ctx->config.tlsConfig.maxVersion == HITLS_VERSION_TLS13); uint32_t getversion = 0; ASSERT_TRUE(HITLS_GetVersionSupport(ctx, &getversion) == HITLS_SUCCESS); ASSERT_TRUE(getversion == ctx->config.tlsConfig.version); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_TLS_CM_HITLS_SetQuietShutdown_HITLS_GetQuietShutdown_API_TC001 * @title Test the HITLS_SetQuietShutdown and HITLS_GetQuietShutdown interfaces * @precon nan * @brief * HITLS_SetQuietShutdown * 1. Input an empty TLS connection handle. Expected result 1 * 2. Input a non-empty TLS connection handle and set mode to an invalid value. Expected result 2 * 3. Input a non-empty TLS connection handle and set mode to a valid value. Expected result 3 * HITLS_GetQuietShutdown * 1. Input an empty TLS connection handle. Expected result 1 * 2. Input an empty mode pointer. Expected result 1 * 3. Input a non-empty TLS connection handle and ensure that the mode pointer is not empty. Expected result 3 * @expect * 1. Return HITLS_NULL_INPUT * 2. Return HITLS_CONFIG_INVALID_SET * 3. Return HITLS_SUCCES */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_SetQuietShutdown_HITLS_GetQuietShutdown_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; int32_t mode = 0; ASSERT_TRUE(HITLS_SetQuietShutdown(ctx, mode) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetQuietShutdown(ctx, &mode) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetQuietShutdown(ctx, NULL) == HITLS_NULL_INPUT); mode = 1; ASSERT_TRUE(HITLS_SetQuietShutdown(ctx, mode) == HITLS_SUCCESS); mode = -1; ASSERT_TRUE(HITLS_SetQuietShutdown(ctx, mode) == HITLS_CONFIG_INVALID_SET); int32_t getMode = -1; ASSERT_TRUE(HITLS_GetQuietShutdown(ctx, &getMode) == HITLS_SUCCESS); ASSERT_TRUE(getMode == true); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_TLS_CM_HITLS_SetDhAutoSupport_API_TC001 * @title Test HITLS_SetDhAutoSupport * @precon nan * @brief * HITLS_SetDhAutoSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Input a non-empty TLS connection handle and set support to an invalid value. Expected result 2 * 3. Input a non-empty TLS connection handle and set support to a valid value. Expected result 3 is displayed. * @expect * 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCES, and isSupportDhAuto is ture * 3. Return HITLS_SUCCES, and isSupportDhAuto is ture or false */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_SetDhAutoSupport_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool support = -1; ASSERT_TRUE(HITLS_SetDhAutoSupport(ctx, support) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); support = true; ASSERT_TRUE(HITLS_SetDhAutoSupport(ctx, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_SetDhAutoSupport(ctx, support) == HITLS_SUCCESS); support = false; ASSERT_TRUE(HITLS_SetDhAutoSupport(ctx, support) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_TMPDH_TC001 * @spec - * @title Test HITLS_SetTmpDh interface * @precon nan * @brief * HITLS_SetTmpDh * 1. Input an empty TLS connection handle. Expected result 1 * 2. Input non-empty TLS connection handle information and leave dhPkey empty. Expected result 1 * 3. Input the non-empty TLS connection handle information and ensure that dhPkey is not empty. Expected result 2 * @expect * 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCES */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_SetTmpDh_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); HITLS_CRYPT_Key *dhPkey = HITLS_CRYPT_GenerateDhKeyBySecbits(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, HITLS_SECURITY_LEVEL_THREE_SECBITS); ASSERT_TRUE(HITLS_SetTmpDh(ctx, dhPkey) == HITLS_NULL_INPUT); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetTmpDh(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetTmpDh(ctx, dhPkey) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test HITLS_GetPeerFinishVerifyData Obtaining Peer VerifyDATA After Link Establishment and Renegotiation Are Complete * @title UT_TLS_CM_HITLS_GetPeerFinishVerifyData_FUNC_TC001 * @precon nan * @brief * 1. Initialize the client and server and obtain the verifyDATA. Expected result 1. * 2. Send a connection setup request. Expected result 2 * 3. Call HITLS_GetPeerFinishVerifyData to obtain and store VerifyData. Expected result 3 * 4. Perform renegotiation. Expected result 4 * 5. Call HITLS_GetPeerFinishVerifyData to obtain VerifyData. Expected result 5 * @expect * 1. Return HITLS_SUCCESS and the len of verifyDATA is 0 * 2. The connection is established. * 3. Return HITLS_SUCCESS and the len of verifyDATA is not 0 * 4. Renegotiation succeeded. * 5. Return HITLS_SUCCESS and the verifyDATA is different from result 1 */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetPeerFinishVerifyData_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); uint8_t verifyDataNew[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataNewSize = 0; uint8_t verifyDataOld[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataOldSize = 0; uint32_t ret = HITLS_GetPeerFinishVerifyData(serverTlsCtx, verifyDataOld, sizeof(verifyDataOld), &verifyDataOldSize); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(verifyDataOldSize, 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ret = HITLS_GetPeerFinishVerifyData(serverTlsCtx, verifyDataOld, sizeof(verifyDataOld), &verifyDataOldSize); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_NE(verifyDataOldSize, 0); ASSERT_TRUE(memcmp(verifyDataNew, verifyDataOld, verifyDataOldSize) != 0); ASSERT_TRUE(memcpy_s(verifyDataOld, sizeof(verifyDataOld), verifyDataNew, verifyDataNewSize) == EOK); ASSERT_TRUE(HITLS_Renegotiate(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateRenegotiationState(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ret = HITLS_GetPeerFinishVerifyData(serverTlsCtx, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(verifyDataNewSize, verifyDataOldSize); ASSERT_TRUE(memcmp(verifyDataNew, verifyDataOld, verifyDataOldSize) != 0); ASSERT_TRUE(memcpy_s(verifyDataOld, sizeof(verifyDataOld), verifyDataNew, verifyDataNewSize) == EOK); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetFinishVerifyData: Obtains the verification data before a connection is established * @title UT_TLS_CM_HITLS_GetFinishVerifyData_FUNC_TC001 * @precon nan * @brief *1. Initialize the client and server. Expected result 1 *2. Call HITLS_GetFinishVerifyData to obtain VerifyData. Expected result 2 * @expect *1. Completing the initialization *2. The interface returns 0. */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetFinishVerifyData_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); uint8_t verifyDataNew[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataNewSize = 0; ASSERT_TRUE(HITLS_GetFinishVerifyData(server->ssl, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize) == HITLS_SUCCESS); ASSERT_EQ(verifyDataNewSize, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetFinishVerifyData Obtain VerifyDATA after connection establishment * @title UT_TLS_CM_HITLS_GetFinishVerifyData_FUNC_TC002 * @precon nan * @brief * 1. Initialize the client and server. Expected result 1 * 2. Send a link setup request. Expected result 2 * 3. Call HITLS_GetFinishVerifyData to obtain VerifyData. Expected result 3 * @expect * 1. Completing the initialization * 2. The connection is established * 3. The value returned by the interface is not 0 */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetFinishVerifyData_FUNC_TC002(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint8_t verifyDataNew[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataNewSize = 0; ASSERT_TRUE(HITLS_GetFinishVerifyData(server->ssl, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize) == HITLS_SUCCESS); ASSERT_NE(verifyDataNewSize, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetFinishVerifyData Obtains VerifyDATA after link establishment and renegotiation. * @title UT_TLS_CM_HITLS_GetFinishVerifyData_FUNC_TC003 * @precon nan * @brief * 1. Initialize the client and server. Expected result * 2. Send a connection setup request. Expected result 2 * 3. Call HITLS_GetFinishVerifyData to obtain and store VerifyData. Expected result 3 * 4. Perform renegotiation. Expected result 4 * 5. Call HITLS_GetFinishVerifyData to obtain VerifyData. Expected result 5 * @expect * 1. Complete the initialization * 2. The link is established * 3. The interface returns a value other than 0 * 4. Renegotiation succeeded * 5. Inconsistent with the first link establishmen */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetFinishVerifyData_FUNC_TC003(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); config->isSupportRenegotiation = true; ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config, 1), HITLS_SUCCESS); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); uint16_t cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256; int32_t ret = HITLS_CFG_SetCipherSuites(config, &cipherSuite, 1); ASSERT_EQ(ret, HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint8_t verifyDataNew[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataNewSize = 0; uint8_t verifyDataOld[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataOldSize = 0; ASSERT_TRUE(HITLS_GetFinishVerifyData(server->ssl, verifyDataOld, sizeof(verifyDataOld), &verifyDataOldSize) == HITLS_SUCCESS); ASSERT_NE(verifyDataOldSize, 0); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); ASSERT_TRUE(HITLS_Renegotiate(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateRenegotiationState(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_GetFinishVerifyData(serverTlsCtx, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize) == HITLS_SUCCESS); ASSERT_TRUE(verifyDataNewSize == verifyDataOldSize); ASSERT_TRUE(memcmp(verifyDataNew, verifyDataOld, verifyDataOldSize) != 0); ASSERT_TRUE(memcpy_s(verifyDataOld, sizeof(verifyDataOld), verifyDataNew, verifyDataNewSize) == EOK); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ int32_t SendHelloReq(HITLS_Ctx *ctx) { uint8_t buf[HS_MSG_HEADER_SIZE] = {0u}; size_t len = HS_MSG_HEADER_SIZE; return REC_Write(ctx, REC_TYPE_HANDSHAKE, buf, len); } /** * @test UT_TLS_CM_HITLS_GetRenegotiationState_FUNC_TC001 * @title Verifying the HITLS_GetRenegotiationState Interface * @precon nan * @brief * 1. After the client and server are initialized, initiate a connection establishment request. Expected result 1 * 2. Call the HITLS_GetRenegotiationState interface to query the renegotiation status. Expected result 2 * 3. The server invokes the hitls_renegotiate interface to initiate renegotiation and invokes the * HITLS_GetRenegotiationState interface to query the renegotiation status on the server. Expected result 3 * 4. After receiving the hello request, the client invokes the HITLS_GetRenegotiationState interface * to query the renegotiation status. Expected result 4 * 5. After receiving the client hello message, the server invokes the HITLS_GetRenegotiationState interface to query * the renegotiation status. Expected result 5 * 6. After the renegotiation is complete, call the HITLS_GetRenegotiationState interface to query the renegotiation * status on the client and server. Expected result 6 * 7. The client invokes the hitls_renegotiate interface to initiate renegotiation and invokes the * HITLS_GetRenegotiationState interface to query the renegotiation status. Expected result 7 * @expect * 1. The connection is successfully established * 2. The return value is false * 3. The return value is true * 4. The return value is true * 5. The return value is true * 6. The return value is flase * 7. The return value is true */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetRenegotiationState_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; uint8_t isRenegotiation = true; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_SetRenegotiationSupport(client->ssl, true); HITLS_SetRenegotiationSupport(server->ssl, true); ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRenegotiationState(client->ssl, &isRenegotiation) == HITLS_SUCCESS); ASSERT_TRUE(isRenegotiation == false); ASSERT_TRUE(HITLS_Renegotiate(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRenegotiationState(server->ssl, &isRenegotiation) == HITLS_SUCCESS); ASSERT_TRUE(isRenegotiation == true); ASSERT_TRUE(SendHelloReq(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_TrasferMsgBetweenLink(server, client) == HITLS_SUCCESS); ASSERT_EQ(HITLS_Connect(client->ssl), HITLS_REC_NORMAL_RECV_BUF_EMPTY); ASSERT_TRUE(HITLS_GetRenegotiationState(server->ssl, &isRenegotiation) == HITLS_SUCCESS); ASSERT_TRUE(isRenegotiation == true); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, false, TRY_SEND_SERVER_HELLO), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRenegotiationState(server->ssl, &isRenegotiation) == HITLS_SUCCESS); ASSERT_TRUE(isRenegotiation == true); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRenegotiationState(server->ssl, &isRenegotiation) == HITLS_SUCCESS); ASSERT_TRUE(isRenegotiation == false); ASSERT_TRUE(HITLS_Renegotiate(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(server->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRenegotiationState(server->ssl, &isRenegotiation) == HITLS_SUCCESS); ASSERT_TRUE(isRenegotiation == true); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test Verifying the HITLS_GetRwstate Interface * @title UT_TLS_CM_HITLS_GetRwstate_FUNC_TC001 * @precon nan * @brief * 1. After the initialization, invoke the HITLS_GetRwstate interface to query data. Expected result 1 * 2. When reading data, set ruio to null, construct a read exception, and call the HITLS_GetRwstate interface for * query. Expected result 2 * 3. When writing data, set uio to null, construct a write exception, and call the HITLS_GetRwstate interface for * query. Expected result 3 * @expect * 1. The returned status is nothing * 2. The returned status is reading * 3. The returned status is writing */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetRwstate_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; uint8_t rwstate = HITLS_READING; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); uint32_t ret = HITLS_GetRwstate(client->ssl, &rwstate); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(rwstate, HITLS_NOTHING); void *tmpUio = client->ssl->rUio; client->ssl->rUio = NULL; BSL_UIO_Free(tmpUio); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen = 0; ret = HITLS_Read(client->ssl, readBuf, READ_BUF_SIZE, &readLen); ret = HITLS_GetRwstate(client->ssl, &rwstate); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(rwstate, HITLS_READING); tmpUio = client->ssl->uio; client->ssl->uio = NULL; BSL_UIO_Free(tmpUio); FRAME_TrasferMsgBetweenLink(client, server); HITLS_Accept(server->ssl); ASSERT_EQ(ret, HITLS_SUCCESS); uint8_t writeBuf[100] = {0}; uint32_t writeLen; ret = HITLS_Write(client->ssl, writeBuf, sizeof(writeBuf), &writeLen); ret = HITLS_GetRwstate(client->ssl, &rwstate); ASSERT_EQ(ret, HITLS_SUCCESS); ASSERT_EQ(rwstate, HITLS_WRITING); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_CLIENTVERIFYSUPPORT_API_TC001 * @title Test the HITLS_SetClientVerifySupport and HITLS_GetClientVerifySupport interfaces. * @precon nan * @brief * HITLS_SetClientVerifySupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer non-empty TLS connection handle information and set support to an invalid value. Expected result 2 * 3. Transfer the non-empty TLS connection handle information and set support to a valid value. Expected result 3 * HITLS_GetClientVerifySupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer an empty isSupport pointer. Expected result 1 * 3. Transfer the non-null TLS connection handle information and ensure that the isSupport pointer is not null. * Expected result 3 * @expect * 1. HITLS_NULL_INPUT is returned * 2. Returns HITLS_SUCCES, isSupportClientVerify is true, and isSupportVerifyNone is false * 3. HITLS_SUCCES is returned, isSupportClientVerify is true or false, and isSupportVerifyNone and isSupportVerifyNone * are mutually exclusive, but can be false at the same time */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_CLIENTVERIFYSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_SetClientVerifySupport(ctx, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetClientVerifySupport(ctx, &isSupport) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetClientVerifySupport(ctx, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_SetClientVerifySupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(config->isSupportVerifyNone == false); support = -1; ASSERT_TRUE(HITLS_SetClientVerifySupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetClientVerifySupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_SetClientVerifySupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetClientVerifySupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_NOCLIENTCERTSUPPORT_API_TC001 * @title Test the HITLS_SetNoClientCertSupport and HITLS_GetClientVerifySupport interfaces * @precon nan * @brief * HITLS_SetNoClientCertSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer non-empty TLS connection handle information and set support to an invalid value. Expected result 2 * 3. Transfer the non-empty TLS connection handle information and set support to a valid value. Expected result 3 * HITLS_GetNoClientCertSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer an empty isSupport pointer. Expected result 1 * 3. Transfer the non-null TLS connection handle information and ensure that the isSupport pointer is not null * Expected result 3 * @expect * 1. HITLS_NULL_INPUT is returned. * 2. HITLS_SUCCES is returned and isSupportNoClientCert is true * 3. Returns HITLS_SUCCES and isSupportNoClientCert is true or false */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_NOCLIENTCERTSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_SetNoClientCertSupport(ctx, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetNoClientCertSupport(ctx, &isSupport) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetNoClientCertSupport(ctx, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_SetNoClientCertSupport(ctx, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_SetNoClientCertSupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetNoClientCertSupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_SetNoClientCertSupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetNoClientCertSupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_VERIFYNONESUPPORT_API_TC001 * @title Test the HITLS_SetVerifyNoneSupport and HITLS_GetVerifyNoneSupport interfaces * @precon nan * @brief * HITLS_SetVerifyNoneSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer non-empty TLS connection handle information and set support to an invalid value. Expected result 2 * 3. Transfer the non-empty TLS connection handle information and set support to a valid value. Expected result 3 * HITLS_GetVerifyNoneSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer an empty isSupport pointer. Expected result 1 * 3. Transfer the non-null TLS connection handle information and ensure that the isSupport pointer is not null * Expected result 3 * @expect * 1. HITLS_NULL_INPUT is returned * 2. Returns HITLS_SUCCES, isSupportVerifyNone is true, and isSupportClientVerify is false * 3. HITLS_SUCCES is returned, isSupportVerifyNone is true or false, isSupportClientVerify and isSupportClientVerify * are mutually exclusive, but can be false at the same time */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_VERIFYNONESUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_SetVerifyNoneSupport(ctx, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetVerifyNoneSupport(ctx, &isSupport) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetVerifyNoneSupport(ctx, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_SetVerifyNoneSupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(config->isSupportClientVerify == false); support = -1; ASSERT_TRUE(HITLS_SetVerifyNoneSupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetVerifyNoneSupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_SetVerifyNoneSupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetVerifyNoneSupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_CLIENTONCEVERIFYSUPPORT_API_TC001 * @title Test the HITLS_SetClientOnceVerifySupport and HITLS_GetClientOnceVerifySupport interfaces. * @precon nan * @brief * HITLS_SetClientOnceVerifySupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer non-empty TLS connection handle information and set support to an invalid value. Expected result 2 * 3. Transfer the non-empty TLS connection handle information and set support to a valid value. Expected result 3 * HITLS_GetClientOnceVerifySupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer an empty isSupport pointer. Expected result 1 * 3. Transfer the non-null TLS connection handle information and ensure that the isSupport pointer is not null. * Expected result 3 * @expect * 1. HITLS_NULL_INPUT is returned * 2. HITLS_SUCCES is returned and isSupportPostHandshakeAuth is true * 3. HITLS_SUCCES is returned and isSupportPostHandshakeAuth is true or false */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_CLIENTONCEVERIFYSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_SetClientOnceVerifySupport(ctx, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetClientOnceVerifySupport(ctx, &isSupport) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetClientOnceVerifySupport(ctx, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_SetClientOnceVerifySupport(ctx, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_SetClientOnceVerifySupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetClientOnceVerifySupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_SetClientOnceVerifySupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetClientOnceVerifySupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test Verifying the HITLS_ClearRenegotiationNum Interface * @title UT_HITLS_CM_HITLS_ClearRenegotiationNum_FUNC_TC001 * @precon nan * @brief * 1. After initialization, invoke the HITLS_ClearRenegotiationNum interface to query data. Expected result 1 * 2. After the link is set up, invoke the HITLS_ClearRenegotiationNum interface to query the link. Expected result 2 * 3. Initiate renegotiation. After the renegotiation is successful, invoke the HITLS_ClearRenegotiationNum interface to check the values of the client and server. Expected result 3 * 4. Initiate another five renegotiations. After the negotiation is complete, invoke the HITLS_ClearRenegotiationNum interface to query the values of the client and server. Expected result 4 * 5. Invoke the HITLS_ClearRenegotiationNum interface again to query the values on the client and server. Expected result 5 * 6. The client initiates renegotiation. The server rejects the renegotiation. Invoke the HITLS_ClearRenegotiationNum interface to query the values of the client and server. Expected result 6 * @expect * 1. The value is 0 * 2. The value is 0 * 3. The value is 1 * 4. The value is 0 * 5. The value is 0 * 6. The value is 1 for the client and 0 for the server */ /* BEGIN_CASE */ void UT_HITLS_CM_HITLS_ClearRenegotiationNum_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256}; HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)); config->isSupportRenegotiation = true; client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); HITLS_Ctx *serverTlsCtx = FRAME_GetTlsCtx(server); HITLS_SetClientRenegotiateSupport(server->ssl, true); uint32_t renegotiationNum = 0; ASSERT_TRUE(HITLS_ClearRenegotiationNum(clientTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 0); ASSERT_TRUE(HITLS_ClearRenegotiationNum(serverTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 0); ASSERT_TRUE(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_ClearRenegotiationNum(clientTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 0); ASSERT_TRUE(HITLS_ClearRenegotiationNum(serverTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 0); uint8_t verifyDataNew[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataNewSize = 0; uint8_t verifyDataOld[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataOldSize = 0; ASSERT_TRUE(HITLS_GetFinishVerifyData(serverTlsCtx, verifyDataOld, sizeof(verifyDataOld), &verifyDataOldSize) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateRenegotiationState(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_GetFinishVerifyData(serverTlsCtx, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize) == HITLS_SUCCESS); ASSERT_TRUE(verifyDataNewSize == verifyDataOldSize); ASSERT_TRUE(memcmp(verifyDataNew, verifyDataOld, verifyDataOldSize) != 0); ASSERT_TRUE(memcpy_s(verifyDataOld, sizeof(verifyDataOld), verifyDataNew, verifyDataNewSize) == EOK); ASSERT_TRUE(HITLS_ClearRenegotiationNum(clientTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 1); ASSERT_TRUE(HITLS_ClearRenegotiationNum(serverTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 1); for (int i = 0; i < 5; ++i) { ASSERT_TRUE(HITLS_Renegotiate(serverTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateRenegotiationState(client, server, true, HS_STATE_BUTT) == HITLS_SUCCESS); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_GetFinishVerifyData(serverTlsCtx, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize) == HITLS_SUCCESS); ASSERT_TRUE(verifyDataNewSize == verifyDataOldSize); ASSERT_TRUE(memcmp(verifyDataNew, verifyDataOld, verifyDataOldSize) != 0); ASSERT_TRUE(memcpy_s(verifyDataOld, sizeof(verifyDataOld), verifyDataNew, verifyDataNewSize) == EOK); } ASSERT_TRUE(HITLS_ClearRenegotiationNum(clientTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 5); ASSERT_TRUE(HITLS_ClearRenegotiationNum(serverTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 5); ASSERT_TRUE(HITLS_ClearRenegotiationNum(clientTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 0); ASSERT_TRUE(HITLS_ClearRenegotiationNum(serverTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 0); ASSERT_TRUE(HITLS_Renegotiate(clientTlsCtx) == HITLS_SUCCESS); serverTlsCtx->negotiatedInfo.isSecureRenegotiation = false; ASSERT_EQ(FRAME_CreateRenegotiation(client, server), HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); ASSERT_TRUE(clientTlsCtx->state == CM_STATE_ALERTED); ASSERT_TRUE(serverTlsCtx->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_GetFinishVerifyData(serverTlsCtx, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize) == HITLS_SUCCESS); ASSERT_TRUE(verifyDataNewSize == verifyDataOldSize); ASSERT_TRUE(memcmp(verifyDataNew, verifyDataOld, verifyDataOldSize) == 0); ASSERT_TRUE(memcpy_s(verifyDataOld, sizeof(verifyDataOld), verifyDataNew, verifyDataNewSize) == EOK); ASSERT_TRUE(HITLS_ClearRenegotiationNum(clientTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 1); ASSERT_TRUE(HITLS_ClearRenegotiationNum(serverTlsCtx, &renegotiationNum) == HITLS_SUCCESS); ASSERT_EQ(renegotiationNum, 0); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetNegotiateGroup: EC cipher suite * @spec - * @title UT_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC001 * @precon nan * @brief * 1. Configure the two ends to use the EC cipher suite. Before connection establishment is complete, invoke the * HITLS_GetNegotiateGroup interface to query the negotiated value. Expected result 1 * 2. Configure the EC cipher suite to be used at both ends. After the connection is established, invoke the * HITLS_GetNegotiateGroup interface to query the negotiated value. Expected result 2 * @expect * 1. The return value is 0 * 2. The returned value is the negotiated value */ /* BEGIN_CASE */ void UT_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC001(int version) { FRAME_Init(); int ret; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint16_t groupId; uint16_t expectedGroupId = HITLS_EC_GROUP_SECP256R1; uint16_t groups_c[] = {expectedGroupId, HITLS_EC_GROUP_SECP384R1}; uint16_t signAlgs_c[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384}; HITLS_CFG_SetGroups(config_c, groups_c, sizeof(groups_c) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_c, signAlgs_c, sizeof(signAlgs_c) / sizeof(uint16_t)); uint16_t groups_s[] = {expectedGroupId, HITLS_EC_GROUP_SECP521R1}; uint16_t signAlgs_s[] = {CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512}; HITLS_CFG_SetGroups(config_s, groups_s, sizeof(groups_s) / sizeof(uint16_t)); HITLS_CFG_SetSignature(config_s, signAlgs_s, sizeof(signAlgs_s) / sizeof(uint16_t)); FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, TRY_RECV_SERVER_HELLO), HITLS_SUCCESS); ret = HITLS_GetNegotiateGroup(client->ssl, &groupId); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_EQ(groupId, 0); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); ret = HITLS_GetNegotiateGroup(client->ssl, &groupId); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_EQ(groupId, expectedGroupId); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test HITLS_GetNegotiateGroup interface uses the RSA cipher suite. * @spec - * @title UT_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC002 * @precon nan * @brief * 1. Set the RSA cipher suite to be used at both ends. After the connection is established, invoke the HITLS_GetNegotiateGroup interface to query the negotiated value. Expected result 1 * @expect * 1. The return value of tls12 is 0. The prerequisite is that the cipher suite does not contain the (EC)DHE. The cipher suite involved in key exchange must have the same group. tls13 is the negotiated group. The current framework supports only ECDHE. Therefore, the connection can be successfully established only when the same EC group exists, The default common curve is HITLS_EC_GROUP_CURVE25519. */ /* BEGIN_CASE */ void UT_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC002(int version) { FRAME_Init(); int ret; HITLS_Config *config_c = GetHitlsConfigViaVersion(version); HITLS_Config *config_s = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); if (version == HITLS_VERSION_TLS12) { ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config_c, true), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetEncryptThenMac(config_s, true), HITLS_SUCCESS); uint16_t cipherSuite = HITLS_RSA_WITH_AES_256_CBC_SHA; ASSERT_EQ(HITLS_CFG_SetCipherSuites(config_c, &cipherSuite, 1), HITLS_SUCCESS); } FRAME_LinkObj *client = FRAME_CreateLink(config_c, BSL_UIO_TCP); FRAME_LinkObj *server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint16_t groupId; uint16_t expectedGroupId = (version == HITLS_VERSION_TLS12) ? 0 : HITLS_EC_GROUP_CURVE25519; ret = HITLS_GetNegotiateGroup(server->ssl, &groupId); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_EQ(groupId, expectedGroupId); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_CIPHERSERVERPREFERENCE_FUNC_TC001 * @title Test the HITLS_SetCipherServerPreference and HITLS_GetCipherServerPreference interfaces * @precon nan * @brief * HITLS_SetCipherServerPreference * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer a non-empty TLS connection handle and set isSupport to an invalid value. Expected result 2 * 3. Transfer a non-empty TLS connection handle and set isSupport to a valid value. Expected result 3 * HITLS_GetCipherServerPreference * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer an empty isSupport pointer. Expected result 1 * 3. Transfer the non-null TLS connection handle information and ensure that the isSupport pointer is not null. * Expected result 3 * @expect * 1. HITLS_NULL_INPUT is returned * 2. HITLS_SUCCES is returned and isSupportServerPreference is true * 3. Returns HITLS_SUCCES and isSupportServerPreference is true or false */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_CIPHERSERVERPREFERENCE_FUNC_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool isSupport = false; bool getIsSupport = false; ASSERT_TRUE(HITLS_SetCipherServerPreference(ctx, isSupport) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetCipherServerPreference(ctx, &getIsSupport) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetCipherServerPreference(ctx, NULL) == HITLS_NULL_INPUT); isSupport = true; ASSERT_TRUE(HITLS_SetCipherServerPreference(ctx, isSupport) == HITLS_SUCCESS); isSupport = -1; ASSERT_TRUE(HITLS_SetCipherServerPreference(ctx, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(config->isSupportServerPreference = true); isSupport = false; ASSERT_TRUE(HITLS_SetCipherServerPreference(ctx, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetCipherServerPreference(ctx, &getIsSupport) == HITLS_SUCCESS); ASSERT_TRUE(getIsSupport == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_RENEGOTIATIONSUPPORT_FUNC_TC001 * @title Test the HITLS_SetRenegotiationSupport and HITLS_GetRenegotiationSupport interfaces. * @precon nan * @brief * HITLS_SetRenegotiationSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer non-empty TLS connection handle information and set support to an invalid value. Expected result 2 * 3. Transfer the non-empty TLS connection handle information and set support to a valid value. Expected result 3 * HITLS_GetRenegotiationSupport * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer an empty isSupport pointer. Expected result 1 * 3. Transfer the non-null TLS connection handle information and ensure that the isSupport pointer is not null. * Expected result 3 * @expect * 1. HITLS_NULL_INPUT is returned * 2. HITLS_SUCCES is returned and isSupportRenegotiation is true * 3. HITLS_SUCCES is returned and isSupportRenegotiation is true or false */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_RENEGOTIATIONSUPPORT_FUNC_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_SetRenegotiationSupport(ctx, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetRenegotiationSupport(ctx, &isSupport) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetRenegotiationSupport(ctx, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_SetRenegotiationSupport(ctx, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_SetRenegotiationSupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRenegotiationSupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_SetRenegotiationSupport(ctx, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRenegotiationSupport(ctx, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_FLIGHTTRANSMITSWITCH_FUNC_TC001 * @title Test the HITLS_SetFlightTransmitSwitch and HITLS_GetFlightTransmitSwitch interfaces * @precon nan * @brief * HITLS_SetFlightTransmitSwitch * 1. Input an empty TLS connection handle. Expected result 1 * 2. Transfer a non-empty TLS connection handle and set isEnable to an invalid value. Expected result 2 * 3. Transfer a non-empty TLS connection handle and set isEnable to a valid value. Expected result 3 * GetFlightTransmitSwitch * 1. Input an empty TLS connection handle. Expected result 1 * 2. Pass an empty getIsEnable pointer. Expected result 1 * 3. Transfer the non-null TLS connection handle information and ensure that the getIsEnable pointer is not null. * Expected result 3 * @expect * 1. HITLS_NULL_INPUT is returned * 2. HITLS_SUCCES is returned and ctx->config.tlsConfig.isFlightTransmitEnable is true * 3. Returns HITLS_SUCCES and ctx->config.tlsConfig.isFlightTransmitEnable is true or false */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_FLIGHTTRANSMITSWITCH_FUNC_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint8_t isEnable = -1; uint8_t getIsEnable = -1; ASSERT_TRUE(HITLS_SetFlightTransmitSwitch(ctx, isEnable) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetFlightTransmitSwitch(ctx, &getIsEnable) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetFlightTransmitSwitch(ctx, NULL) == HITLS_NULL_INPUT); isEnable = 1; ASSERT_TRUE(HITLS_SetFlightTransmitSwitch(ctx, isEnable) == HITLS_SUCCESS); isEnable = -1; ASSERT_TRUE(HITLS_SetFlightTransmitSwitch(ctx, isEnable) == HITLS_SUCCESS); ASSERT_TRUE(ctx->config.tlsConfig.isFlightTransmitEnable = true); isEnable = 0; ASSERT_TRUE(HITLS_SetFlightTransmitSwitch(ctx, isEnable) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetFlightTransmitSwitch(ctx, &getIsEnable) == HITLS_SUCCESS); ASSERT_TRUE(getIsEnable == false); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** * @test UT_HITLS_CM_SET_GET_SetMaxCertList_FUNC_TC001 * @title HTLS_CFG_SetMaxCertList, HITLS_CFG_GetMaxCertList, HITLS_SetMaxCertList, and HITLS_GetMaxCertList APIs * @precon nan * @brief * 1. Apply for and initialize config and ctx * 2. Set the certificate chain length config to null and invoke the HITLS_CFG_SetMaxCertList interface * 3. Invoke the HITLS_CFG_GetMaxCertList interface and check the output parameter value * 4. Set the maximum length of the certificate chain by calling the HITLS_CFG_SetMaxCertList interface * 5. Invoke the HITLS_CFG_GetMaxCertList interface and check the output parameter value * 6. Set the minimum certificate chain length by calling the HITLS_CFG_SetMaxCertList interface * 7. Invoke the HITLS_CFG_GetMaxCertList interface and check the output parameter value * 8. Use the HITLS_SetMaxCertList and HITLS_GetMaxCertList interfaces to repeat the preceding test * @expect * 1. Initialization succeeds * 2. HITLS_NULL_INPUT is returned * 3. HITLS_NULL_INPUT is returned * 4. The interface returns HITLS_SUCCESS * 5. The value of MaxCertList returned by the interface is 2 ^ 32 - 1 * 6. The interface returns the HITLS_SUCCESS * 7. The value of MaxCertList returned by the interface is 0 * 8. Same as above */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_SetMaxCertList_FUNC_TC001() { FRAME_Init(); HITLS_Config *tlsConfig; HITLS_Ctx *ctx = NULL; tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); uint32_t maxSize; // The config parameter is empty. ASSERT_TRUE(HITLS_CFG_SetMaxCertList(NULL, MAX_CERT_LIST) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMaxCertList(NULL, &maxSize) == HITLS_NULL_INPUT); // Set the maximum value to 2 ^ 32 - 1. ASSERT_TRUE(HITLS_CFG_SetMaxCertList(tlsConfig, MAX_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxCertList(tlsConfig, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MAX_CERT_LIST); // Set the minimum value to 0. ASSERT_TRUE(HITLS_CFG_SetMaxCertList(tlsConfig, MIN_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxCertList(tlsConfig, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MIN_CERT_LIST); // The config parameter is empty. ASSERT_TRUE(HITLS_SetMaxCertList(NULL, MAX_CERT_LIST) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetMaxCertList(NULL, &maxSize) == HITLS_NULL_INPUT); // Set the maximum value to 2 ^ 32 - 1. ASSERT_TRUE(HITLS_SetMaxCertList(ctx, MAX_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetMaxCertList(ctx, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MAX_CERT_LIST); // Set the minimum value to 0. ASSERT_TRUE(HITLS_SetMaxCertList(ctx, MIN_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetMaxCertList(ctx, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MIN_CERT_LIST); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ void ExampleInfoCallback(const HITLS_Ctx *ctx, int32_t eventType, int32_t value) { (void)ctx; (void)eventType; (void)value; } uint64_t Test_RecordPaddingCb(HITLS_Ctx *ctx, int32_t type, uint64_t length, void *arg) { (void)ctx; (void)type; (void)length; (void)arg; return HITLS_SUCCESS; } /* @ * @test UT_TLS_CM_InfoCb_API_TC001 * @title InfoCb Interface Parameter Test * @precon nan * @brief 1. Use the HITLS_GetInfoCb without HITLS_CFG_SetInfoCb. Expected result 1 is obtained. 2. Use the HITLS_SetInfoCb interface to set callback. Expected result 2 3. Use the HITLS_GetInfoCb . Expected result 3 4. Use the HITLS_GetInfoCb with the parameter is NULL . Expected result 4 * @expect 1. Return the NULL. 2. Return the HITLS_SUCCESS 3. Return value is not NULL. 4. Return the NULL. @ */ /* BEGIN_CASE */ void UT_TLS_CM_InfoCb_API_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); FRAME_LinkObj *client = FRAME_CreateLink(config, BSL_UIO_UDP); ASSERT_TRUE(client != NULL); HITLS_Ctx *clientTlsCtx = FRAME_GetTlsCtx(client); ASSERT_TRUE(clientTlsCtx != NULL); HITLS_InfoCb infoCallBack = HITLS_GetInfoCb(clientTlsCtx); ASSERT_TRUE(infoCallBack == NULL); int32_t ret = HITLS_SetInfoCb(clientTlsCtx, ExampleInfoCallback); ASSERT_TRUE(ret == HITLS_SUCCESS); infoCallBack = HITLS_GetInfoCb(clientTlsCtx); ASSERT_TRUE(infoCallBack != NULL); infoCallBack = HITLS_GetInfoCb(NULL); ASSERT_TRUE(infoCallBack == NULL); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); } /* END_CASE */ #define MSG_CB_PRINT_LEN 500 void msg_callback(int32_t writePoint, int32_t tlsVersion, int32_t contentType, const void *msg, uint32_t msgLen, HITLS_Ctx *ctx, void *arg) { (void)writePoint; (void)tlsVersion; (void)contentType; (void)msg; (void)msgLen; (void)ctx; (void)arg; } /* @ * @test UT_TLS_CM_SetMsgCb_API_TC001 * @title HITLS_SetMsgCb Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2. Use the HITLS_SetMsgCb interface to set callback. (Expected result 2) * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetMsgCb_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = NULL; ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetMsgCb(NULL, msg_callback), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetMsgCb(ctx, msg_callback), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_GetError_API_TC001 * @title HITLS_GetError Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2.Invoke the HITLS_GetError interface and send the return value. The expected result 2 is obtained * @expect 1. Return the HITLS_ERR_SYSCALL message. 2. Link error codes are returned @ */ /* BEGIN_CASE */ void UT_TLS_CM_GetError_API_TC001(void) { FRAME_Init(); HITLS_Ctx *ctx = NULL; HITLS_Config *config = NULL; config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetError(NULL, HITLS_SUCCESS) == HITLS_ERR_SYSCALL); ASSERT_TRUE(HITLS_GetError(ctx, HITLS_SUCCESS) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SetAlpnProtos_API_TC001 * @title HITLS_SetAlpnProtos Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. * @expect 1. Return the HITLS_NULL_INPUT message. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetAlpnProtos_API_TC001() { HitlsInit(); uint8_t * alpnProtosname = (uint8_t *)"vpn|http"; uint32_t alpnProtosnameLen = sizeof(alpnProtosname); ASSERT_TRUE(HITLS_SetAlpnProtos(NULL, alpnProtosname, alpnProtosnameLen) == HITLS_NULL_INPUT); EXIT: return; } /* END_CASE */ uint32_t SetPskClientCallback(HITLS_Ctx *ctx, const uint8_t *hint, uint8_t *identity, uint32_t maxIdentityLen, uint8_t *psk, uint32_t maxPskLen) { (void)ctx; (void)hint; (void)identity; (void)maxIdentityLen; (void)psk; (void)maxPskLen; return HITLS_SUCCESS; } /* @ * @test UT_TLS_CM_SetPskClientCallback_API_TC001 * @title HITLS_SetPskClientCallback Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2. Use the HITLS_SetPskClientCallback interface to set callback. Expected result 2 * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetPskClientCallback_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = NULL; ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetPskClientCallback(NULL, SetPskClientCallback), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetPskClientCallback(ctx, SetPskClientCallback), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ static uint32_t SetPskServerCallback(HITLS_Ctx *ctx, const uint8_t *identity, uint8_t *psk, uint32_t maxPskLen) { (void)ctx; (void)identity; (void)psk; (void)maxPskLen; return HITLS_SUCCESS; } /* @ * @test UT_TLS_CM_SetPskServerCallback_API_TC001 * @title HITLS_SetPskServerCallback Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2. Use the HITLS_SetPskServerCallback interface to set callback. Expected result 2 * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetPskServerCallback_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = NULL; ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetPskServerCallback(NULL, SetPskServerCallback), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetPskServerCallback(ctx, SetPskServerCallback), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ static int32_t SetPskUsePsksessionCallback(HITLS_Ctx *ctx, uint32_t hashAlgo, const uint8_t **id, uint32_t *idLen, HITLS_Session **session) { (void)ctx; (void)hashAlgo; (void)id; (void)idLen; (void)session; return HITLS_SUCCESS; } /* @ * @test UT_TLS_CM_SetPskUseSessionCallback_API_TC001 * @title HITLS_SetPskUseSessionCallback Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2. Use the HITLS_SetPskUseSessionCallback interface to set callback. Expected result 2 * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetPskUseSessionCallback_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = NULL; ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetPskUseSessionCallback(NULL, SetPskUsePsksessionCallback), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetPskUseSessionCallback(ctx, SetPskUsePsksessionCallback), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ int32_t SetPskFindSessionCallback(HITLS_Ctx *ctx, const uint8_t *identity, uint32_t identityLen, HITLS_Session **session) { (void)ctx; (void)identity; (void)identityLen; (void)session; return HITLS_SUCCESS; } /* @ * @test UT_TLS_CM_SetPskFindSessionCallback_API_TC001 * @title HITLS_SetPskFindSessionCallback Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2. Use the HITLS_SetPskFindSessionCallback interface to set callback. Expected result 2 * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetPskFindSessionCallback_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = NULL; ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetPskFindSessionCallback(NULL, SetPskFindSessionCallback), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetPskFindSessionCallback(ctx, SetPskFindSessionCallback), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SetNeedCheckPmsVersion_API_TC001 * @title HITLS_SetNeedCheckPmsVersion Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2. Use the HITLS_SetNeedCheckPmsVersion interface to set parameter true. Expected result 2 * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetNeedCheckPmsVersion_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = NULL; ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetNeedCheckPmsVersion(NULL, true), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetNeedCheckPmsVersion(ctx, true), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SetPskIdentityHint_API_TC001 * @title HITLS_SetPskIdentityHint Interface Parameter Test * @precon nan * @brief 1. Set ctx to NULL. Expected result 1 is obtained. 2. Use the HITLS_SetPskIdentityHint interface to set parameter. Expected result 2 * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CM_SetPskIdentityHint_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); uint8_t * identityH = (uint8_t *)"123456"; uint32_t identityHintLen = strlen((char *)identityH); ASSERT_TRUE(HITLS_SetPskIdentityHint(ctx, identityH, identityHintLen) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); return; } /* END_CASE */ /* @ * @test UT_TLS_CM_SETTICKETNUMS_API_TC001 * @title HITLS_SetTicketNums interface test * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Invoke the HITLS_SetTicketNums interface and set the input parameter of the HITLS_Ctx to NULL. * 3. Invoke the HITLS_SetTicketNums interface and set the input parameter of the ticketNums to 0. * 4. Invoke the HITLS_SetTicketNums interface and set normal ticketNums. * @expect * 1. Initialization succeeded. * 2. The interface returns HITLS_NULL_INPUT. * 3. The interface returns HITLS_SUCCESS. * 4. The interface returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SETTICKETNUMS_API_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetTicketNums(NULL, 0), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetTicketNums(ctx, 0), HITLS_SUCCESS); ASSERT_EQ(HITLS_SetTicketNums(ctx, 3), HITLS_SUCCESS); ASSERT_EQ(HITLS_SetTicketNums(ctx, 100), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_GETTICKETNUMS_API_TC001 * @title HITLS_GetTicketNums interface test * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Invoke the HITLS_GetRecordPaddingCb interface and set the input parameter of the HITLS_Ctx to NULL. * 3. Invoke the HITLS_GetRecordPaddingCb interface to get the default ticketNums. * 4. Invoke the HITLS_GetRecordPaddingCb interface and set normal ticketNums. * 5. Invoke the HITLS_GetRecordPaddingCb interface to get the ticketNums * @expect * 1. Initialization succeeded. * 2. The interface returns ticketNums is 2. * 3. The interface returns HITLS_NULL_INPUT. * 4. The interface returns HITLS_SUCCESS. * 5. Consistent with the configured ticketNums. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GETTICKETNUMS_API_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS13Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); const int defaultNum = 2; int TicketNum = 3; ASSERT_EQ(HITLS_GetTicketNums(NULL), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_GetTicketNums(ctx), defaultNum); ASSERT_EQ(HITLS_SetTicketNums(ctx, TicketNum), HITLS_SUCCESS); ASSERT_EQ(HITLS_GetTicketNums(ctx), TicketNum); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SETRECORDPADDINGCB_API_TC001 * @title HITLS_SetRecordPaddingCb interface test * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Invoke the HITLS_SetRecordPaddingCb interface and set the input parameter of the HITLS_Ctx to NULL. * 3. Invoke the HITLS_SetRecordPaddingCb interface and set the input parameter of the callback to NULL. * 4. Invoke the HITLS_SetRecordPaddingCb interface and set normal callback. * @expect * 1. Initialization succeeded. * 2. The interface returns HITLS_NULL_INPUT. * 3. The interface returns HITLS_SUCCESS. * 4. The interface returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SETRECORDPADDINGCB_API_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetRecordPaddingCb(NULL, 0), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetRecordPaddingCb(ctx, NULL), HITLS_SUCCESS); ASSERT_EQ(HITLS_SetRecordPaddingCb(ctx, Test_RecordPaddingCb), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_GETRECORDPADDINGCB_API_TC001 * @title HITLS_GetRecordPaddingCb interface test * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Invoke the HITLS_GetRecordPaddingCb interface to get the default callback. * 3. Invoke the HITLS_GetRecordPaddingCb interface and set the input parameter of the HITLS_Ctx to NULL. * 4. Invoke the HITLS_GetRecordPaddingCb interface and set normal callback. * 5. Invoke the HITLS_GetRecordPaddingCb interface to get the callback * @expect * 1. Initialization succeeded. * 2. The interface returns NULL. * 3. The interface returns HITLS_NULL_INPUT. * 4. The interface returns HITLS_SUCCESS. * 5. Consistent with the configured callback. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GETRECORDPADDINGCB_API_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_GetRecordPaddingCb(ctx), NULL); ASSERT_EQ(HITLS_GetRecordPaddingCb(NULL), NULL); ASSERT_TRUE(HITLS_SetRecordPaddingCb(ctx, Test_RecordPaddingCb) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetRecordPaddingCb(ctx) == Test_RecordPaddingCb); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SETRECORDPADDINGCBARG_API_TC001 * @title HITLS_SetRecordPaddingCbArg interface test * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Invoke the HITLS_SetRecordPaddingCbArg interface and set the input parameter of the HITLS_Ctx to NULL. * 3. Invoke the HITLS_SetRecordPaddingCbArg interface and set the input parameter of the RecordPaddingArg to NULL. * 4. Invoke the HITLS_SetRecordPaddingCbArg interface and set normal recordPaddingArg. * @expect * 1. Initialization succeeded. * 2. The interface returns HITLS_NULL_INPUT. * 3. The interface returns HITLS_SUCCESS. * 4. The interface returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SETRECORDPADDINGCBARG_API_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); uint32_t arg = 1; ASSERT_EQ(HITLS_SetRecordPaddingCbArg(NULL, &arg), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetRecordPaddingCbArg(ctx, NULL), HITLS_SUCCESS); ASSERT_EQ(HITLS_SetRecordPaddingCbArg(ctx, &arg), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_GETRECORDPADDINGCBARG_API_TC001 * @title HITLS_GetRecordPaddingCbArg interface test * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Invoke the HITLS_GetRecordPaddingCbArg interface to get the default recordPaddingArg. * 3. Invoke the HITLS_GetRecordPaddingCbArg interface and set the input parameter of the HITLS_Ctx to NULL. * 4. Invoke the HITLS_GetRecordPaddingCbArg interface and set normal recordPaddingArg. * 5. Invoke the HITLS_GetRecordPaddingCbArg interface to get the recordPaddingArg. * @expect * 1. Initialization succeeded. * 2. The interface returns NULL. * 3. The interface returns HITLS_NULL_INPUT. * 4. The interface returns HITLS_SUCCESS. * 5. Consistent with the configured recordPaddingArg. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GETRECORDPADDINGCBARG_API_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); int arg = 1; ASSERT_EQ(HITLS_GetRecordPaddingCbArg(ctx), NULL); ASSERT_EQ(HITLS_GetRecordPaddingCbArg(NULL), NULL); ASSERT_EQ(HITLS_SetRecordPaddingCbArg(ctx, &arg), HITLS_SUCCESS); ASSERT_EQ(*(int*)HITLS_GetRecordPaddingCbArg(ctx) , arg); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SETCLOSECHECKKEYUSAGE_API_TC001 * @title HITLS_SetCheckKeyUsage interface test * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Invoke the HITLS_SetCheckKeyUsage interface and set the input parameter of the HITLS_Ctx to NULL. * 3. Invoke the HITLS_SetCheckKeyUsage interface and set the input parameter of the isClose to true. * 4. Invoke the HITLS_SetCheckKeyUsage interface and set the input parameter of the isClose to false. * @expect * 1. Initialization succeeded. * 2. The interface returns HITLS_NULL_INPUT. * 3. The interface returns HITLS_SUCCESS. * 4. The interface returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SETCLOSECHECKKEYUSAGE_API_TC001() { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_EQ(HITLS_SetCheckKeyUsage(NULL, true), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetCheckKeyUsage(ctx, true), HITLS_SUCCESS); ASSERT_EQ(HITLS_SetCheckKeyUsage(ctx, false), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ static int32_t STUB_ChangeState(TLS_Ctx *ctx, uint32_t nextState) { int32_t ret = HITLS_SUCCESS; if (HS_STATE_BUTT == nextState) { if (true == ctx->isClient) { ctx->hsCtx->hsMsg = NULL; ret = HITLS_REC_NORMAL_RECV_BUF_EMPTY; } } HS_Ctx *hsCtx = (HS_Ctx *)ctx->hsCtx; hsCtx->state = nextState; return ret; } static bool StateCompare(FRAME_LinkObj *link, HITLS_HandshakeState state) { if ((link->ssl->hsCtx != NULL) && (link->ssl->hsCtx->state == state)) { if (state != TRY_RECV_FINISH) { return true; } } return false; } /** @ * @test UT_TLS_CM_HITLS_DOHANDSHAKE_API_TC001 * @title HITLS_DoHandShake Interface Test * @precon nan * @brief 1、Invoke the HITLS_DoHandShake to create tls connect. The expected result 1 is obtained * @expect 1、connect success @ */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_DOHANDSHAKE_API_TC001() { FRAME_Init(); HITLS_Config *config = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); int32_t clientRet; int32_t serverRet; int32_t ret; uint32_t count = 0; FuncStubInfo tmpRpInfo = { 0 }; STUB_Init(); STUB_Replace(&tmpRpInfo, HS_ChangeState, STUB_ChangeState); HITLS_SetEndPoint(client->ssl, true); do { if (StateCompare(client, HS_STATE_BUTT)) { ret = HITLS_SUCCESS; break; } clientRet = HITLS_DoHandShake(client->ssl); if (clientRet != HITLS_SUCCESS) { ret = clientRet; if ((clientRet != HITLS_REC_NORMAL_IO_BUSY) && (clientRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(client, server); if (ret != HITLS_SUCCESS) { break; } if (StateCompare(server, HS_STATE_BUTT)) { ret = HITLS_SUCCESS; break; } serverRet = HITLS_DoHandShake(server->ssl); if (serverRet != HITLS_SUCCESS) { ret = serverRet; if ((serverRet != HITLS_REC_NORMAL_IO_BUSY) && (serverRet != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { break; } } ret = FRAME_TrasferMsgBetweenLink(server, client); if (ret != HITLS_SUCCESS) { break; } if (clientRet == HITLS_SUCCESS && serverRet == HITLS_SUCCESS) { ret = HITLS_SUCCESS; break; } count++; ret = HITLS_INTERNAL_EXCEPTION; } while (count < 40); ASSERT_EQ(ret, HITLS_SUCCESS); EXIT: STUB_Reset(&tmpRpInfo); HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CM_SECURITY_SECURITYLEVEL_API_TC001 * @title HITLS_GetSecurityLevel and HITLS_CFG_GetSecurityLevel Interface Test * @precon nan * @brief HITLS_GetSecurityLevel 1、Invoke HITLS_GetSecurityLevel to obtain the default security level. The expected result 1 is obtained 2、Check the obtained security level. The expected result 2 is obtained HITLS_CFG_GetSecurityLevel 3、Invoke HITLS_CFG_GetSecurityLevel to obtain the default security level. The expected result 1 is obtained 4、Check the obtained security level. The expected result 2 is obtained * @expect 1、return HITLS_SUCCESS 2、The security level is 1 @ */ /* BEGIN_CASE */ void UT_TLS_CM_SECURITY_SECURITYLEVEL_API_TC001() { HitlsInit(); HITLS_Ctx *ctx = NULL; HITLS_Config *Config; int32_t level; Config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(Config != NULL); ctx = HITLS_New(Config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetSecurityLevel(ctx, &level) == HITLS_SUCCESS); ASSERT_TRUE(level == 1); ASSERT_TRUE(HITLS_CFG_GetSecurityLevel(Config, &level) == HITLS_SUCCESS); ASSERT_TRUE(level == 1); EXIT: HITLS_CFG_FreeConfig(Config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CM_SECURITY_SECURITYLEVEL_API_TC002 * @title HITLS_SetSecurityLevel and HITLS_CFG_SetSecurityLevel Interface Parameter Test * @precon nan * @brief HITLS_SetSecurityLevel 1、Invoke the HITLS_SetSecurityLevel to configure the security level.The expected result 1 is obtained 2、Invoke HITLS_GetSecurityLevel to obtain the default security level. The expected result 2 is obtained 3、Check the obtained security level. The expected result 3 is obtained HITLS_CFG_SetSecurityLevel 4、Invoke the HITLS_CFG_SetSecurityLevel to configure the security level.The expected result 1 is obtained 5、Invoke HITLS_GetSecurityLevel to obtain the default security level. The expected result 2 is obtained 6、Check the obtained security level. The expected result 3 is obtained * @expect 1、return HITLS_SUCCESS 2、return HITLS_SUCCESS 3、The security level is equal to the configured security level. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SECURITY_SECURITYLEVEL_API_TC002() { HitlsInit(); HITLS_Ctx *ctx = NULL; HITLS_Config *Config; int32_t level; Config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(Config != NULL); ctx = HITLS_New(Config); ASSERT_TRUE(ctx != NULL); for(int32_t i = 0; i <= 5; i++){ ASSERT_TRUE(HITLS_SetSecurityLevel(ctx, i) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetSecurityLevel(ctx, &level) == HITLS_SUCCESS); ASSERT_TRUE(level == i); ASSERT_TRUE(HITLS_CFG_SetSecurityLevel(Config, i) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetSecurityLevel(Config, &level) == HITLS_SUCCESS); ASSERT_TRUE(level == i); } EXIT: HITLS_CFG_FreeConfig(Config); HITLS_Free(ctx); } /* END_CASE */ int32_t TEST_HITLS_SecurityCb(const HITLS_Ctx *ctx, const HITLS_Config *config, int32_t option, int32_t bits, int32_t id, void *other, void *exData) { (void)ctx; (void)config; (void)option; (void)bits; (void)id; (void)other; (void)exData; return HITLS_SUCCESS; } /** @ * @test UT_TLS_CM_SECURITY_SECURITYCB_API_TC001 * @title HITLS_SetSecurityCb HITLS_SetSecurityExData HITLS_GetSecurityCb and HITLS_GetSecurityExData Interface Test * @precon nan * @brief 1、Invoke the HITLS_SetSecurityCb interface and set the first parameter to NULL. The expected result 1 is obtained 2、Invoke the HITLS_SetSecurityCb interface and transfer the first parameter to a normal parameter. The expected result 2 is obtained 3、Invoke the HITLS_SetSecurityExData interface and set the first parameter to NULL. The expected result 3 is obtained 4、Invoke the HITLS_SetSecurityExData interface and transfer the first parameter to a normal parameter. The expected result 4 is obtained 5、Invoke the HITLS_GetSecurityCb interface and set the parameter to NULL. The expected result 5 is obtained 6、Invoke the HITLS_GetSecurityCb interface and transfer the parameter to a normal parameter. The expected result 5 is obtained 7、Invoke the HITLS_GetSecurityExData interface and set the parameter to NULL. The expected result 7 is obtained 8、Invoke the HITLS_GetSecurityExData interface and transfer the parameter to a normal parameter. The expected result 8 is obtained * @expect 1、return HITLS_NULL_INPUT 2、 return HITLS_SUCCESS 3、 return HITLS_NULL_INPUT 4、 return HITLS_SUCCESS 5、 return NULL 6、 The returned value is equal to the configured value TEST_HITLS_SecurityCb. 7、 return NULL 8、 The returned value is equal to the configured value securityExData. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SECURITY_SECURITYCB_API_TC001() { HitlsInit(); HITLS_Ctx *ctx = NULL; HITLS_Config *Config; Config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(Config != NULL); ctx = HITLS_New(Config); int32_t userdata = 0; void *securityExData = &userdata; ASSERT_EQ(HITLS_SetSecurityCb(NULL, TEST_HITLS_SecurityCb), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetSecurityCb(ctx, TEST_HITLS_SecurityCb), HITLS_SUCCESS); ASSERT_EQ(HITLS_SetSecurityExData(NULL, securityExData), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_SetSecurityExData(ctx, securityExData), HITLS_SUCCESS); ASSERT_EQ(HITLS_GetSecurityCb(NULL), NULL); ASSERT_EQ(HITLS_GetSecurityCb(ctx), TEST_HITLS_SecurityCb); ASSERT_EQ(HITLS_GetSecurityExData(NULL), NULL); ASSERT_EQ(HITLS_GetSecurityExData(ctx), securityExData); EXIT: HITLS_CFG_FreeConfig(Config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CM_SECURITY_SECURITYCB_API_TC002 * @title HITLS_CFG_SetSecurityCb HITLS_CFG_SetSecurityExData HITLS_CFG_GetSecurityCb and HITLS_CFG_GetSecurityExData Interface Test * @precon nan * @brief 1、Invoke the HITLS_CFG_SetSecurityCb interface and set the first parameter to NULL. The expected result 1 is obtained 2、Invoke the HITLS_CFG_SetSecurityCb interface and transfer the first parameter to a normal parameter. The expected result 2 is obtained 3、Invoke the HITLS_CFG_SetSecurityExData interface and set the first parameter to NULL. The expected result 3 is obtained 4、Invoke the HITLS_CFG_SetSecurityExData interface and transfer the first parameter to a normal parameter. The expected result 4 is obtained 5、Invoke the HITLS_CFG_GetSecurityCb interface and set the parameter to NULL. The expected result 5 is obtained 6、Invoke the HITLS_CFG_GetSecurityCb interface and transfer the parameter to a normal parameter. The expected result 5 is obtained 7、Invoke the HITLS_CFG_GetSecurityExData interface and set the parameter to NULL. The expected result 7 is obtained 8、Invoke the HITLS_CFG_GetSecurityExData interface and transfer the parameter to a normal parameter. The expected result 8 is obtained * @expect 1、return HITLS_NULL_INPUT 2、 return HITLS_SUCCESS 3、 return HITLS_NULL_INPUT 4、 return HITLS_SUCCESS 5、 return NULL 6、 The returned value is equal to the configured value TEST_HITLS_SecurityCb. 7、 return NULL 8、 The returned value is equal to the configured value securityExData. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SECURITY_SECURITYCB_API_TC002() { HitlsInit(); HITLS_Config *Config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(Config != NULL); int32_t userdata = 0; void *securityExData = &userdata; ASSERT_EQ(HITLS_CFG_SetSecurityCb(NULL, TEST_HITLS_SecurityCb), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_CFG_SetSecurityCb(Config, TEST_HITLS_SecurityCb), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_SetSecurityExData(NULL, securityExData), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_CFG_SetSecurityExData(Config, securityExData), HITLS_SUCCESS); ASSERT_EQ(HITLS_CFG_GetSecurityCb(NULL), NULL); ASSERT_EQ(HITLS_CFG_GetSecurityCb(Config), TEST_HITLS_SecurityCb); ASSERT_EQ(HITLS_CFG_GetSecurityExData(NULL), NULL); ASSERT_EQ(HITLS_CFG_GetSecurityExData(Config), securityExData); EXIT: HITLS_CFG_FreeConfig(Config); } /* END_CASE */ /* @ * @test UT_TLS_CM_IS_DTLS_API_TC001 * @title Test HITLS_IsDtls * @precon nan * @brief HITLS_IsDtls * 1. Input an empty TLS connection handle. Expected result 1. * 2. Transfer the non-empty TLS connection handle information and leave isDtls blank. Expected result 1. * 3. Transfer the non-empty TLS connection handle information. The isDtls parameter is not empty. Expected result 2. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CM_IS_DTLS_API_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint8_t isDtls = 0; ASSERT_TRUE(HITLS_IsDtls(ctx, &isDtls) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_IsDtls(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_IsDtls(ctx, &isDtls) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /*@ * @test UT_TLS_CM_GET_SELECTEDALPNPROTO_API_TC001 * * @title test HITLS_GetSelectedAlpnProto interface * @brief * 1. Construct the CTX configuration. Expected result 1. * 2. Construct the CTX connection handle. Expected result 1. * 3. tls connection handle is NULL, Invoke the HITLS_GetSelectedAlpnProto interface. Expected result 2. * 4. proto is NULL ,invoke the HITLS_CFG_SetSessionIdCtx interface.Expected result 2. * 5. protoLen is NULL, Invoke the HITLS_GetSessionTicketKey interface.Expected result 2 * @expect 1. Return not NULL. * 2. Return not HITLS_NULL_INPUT. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_SELECTEDALPNPROTO_API_TC001() { HitlsInit(); HITLS_Config *tlsConfig; HITLS_Ctx *ctx = NULL; tlsConfig = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); uint8_t * alpnProtosname = (uint8_t *)"vpn|http"; uint32_t alpnProtosnameLen = sizeof(alpnProtosname); ASSERT_TRUE(HITLS_GetSelectedAlpnProto(NULL, &alpnProtosname, &alpnProtosnameLen) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_GetSelectedAlpnProto(ctx, NULL, &alpnProtosnameLen), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_GetSelectedAlpnProto(ctx, &alpnProtosname, NULL), HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); return; } /* END_CASE */ #define DATA_MAX_LEN 1024 /*@ * @test UT_TLS_CM_GET_SET_SESSIONTICKETKEY_API_TC001 * * @title test HITLS_SetSessionTicketKey/HITLS_GetSessionTicketKey interface * @brief 1. Construct the CTX connection handle. Expected result 1. * 2. tls connection handle is NULL, Invoke the HITLS_SetSessionTicketKey interface. Expected result 2. * 3. tls connection handle is NULL, Invoke the HITLS_GetSessionTicketKey interface.Expected result 2. * @expect 1. Return not NULL. * 2. Return HITLS_NULL_INPUT. @ */ /* BEGIN_CASE */ void UT_TLS_CM_GET_SET_SESSIONTICKETKEY_API_TC001(int version) { FRAME_Init(); uint8_t key[] = "748ab9f3dc1a23"; HITLS_Config *config = GetHitlsConfigViaVersion(version); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); uint8_t getKey[DATA_MAX_LEN] = {0}; uint32_t getKeySize = DATA_MAX_LEN; uint32_t outSize = 0; uint32_t ticketKeyRandLen = HITLS_TICKET_KEY_NAME_SIZE + HITLS_TICKET_KEY_SIZE + HITLS_TICKET_KEY_SIZE; ASSERT_TRUE(HITLS_SetSessionTicketKey(NULL, key, ticketKeyRandLen) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetSessionTicketKey(NULL, getKey, getKeySize, &outSize) == HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_SET_SESSIONIDCTX_API_TC001 * * @title test HITLS_CFG_SetSessionIdCtx interface * @precon nan * @brief 1. Construct the CTX connection handle. Expected result 1. * 2. config is NULL, Invoke the HITLS_CFG_SetSessionIdCtx interface. Expected result 4. * 3. invoke the HITLS_CFG_SetSessionIdCtx interface.Expected result 2. * 4. tls connection handle is NULL, Invoke the HITLS_SetSessionIdCtx interface.Expected * result 4. * 5. Invoke the HITLS_SetSessionIdCtx interface. Expected result 2. * @expect 1. Return not NULL. * 2. Return not HITLS_NULL_INPUT. * 3. Return NULL. * 4. Return HITLS_NULL_INPUT. @ */ /* BEGIN_CASE */ void UT_TLS_CM_SET_SESSIONIDCTX_API_TC001(int version) { FRAME_Init(); char *key = "748ab9f3dc1a23"; HITLS_Config *config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); HITLS_Ctx *ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); uint32_t keyLen = strlen(key); ASSERT_TRUE(HITLS_CFG_SetSessionIdCtx(NULL, (const uint8_t *)key, keyLen)== HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetSessionIdCtx(config, (const uint8_t *)key, keyLen)!= HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetSessionIdCtx(NULL, (const uint8_t *)key, keyLen)== HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetSessionIdCtx(ctx, (const uint8_t *)key, keyLen)!= HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_TLS_CM_HITLS_GetCertificate_API_TC001 * @title Cover the input parameter of the HITLS_GetCertificate interface. * @precon nan * @brief 1. Invoke the HITLS_GetCertificate interface and leave ctx blank. Expected result 1. * 2. Invoke the HITLS_GetPeerCertificate interface and leave ctx blank. Expected result 1. * 3. Invoke the HITLS_GetPeerCertificate interface. The value of ctx is not empty and the value of ctx->session * is empty. Expected result 1. * 4. Invoke the HITLS_GetPeerCertChain interface and leave ctx blank. Expected result 1. * 5. Invoke the HITLS_GetPeerCertChain interface. The value of ctx is not empty and the value of ctx->session is * empty. Expected result 1. * @expect 1.Return NULL @ */ /* BEGIN_CASE */ void UT_TLS_CM_HITLS_GetCertificate_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetCertificate(NULL) == NULL); ASSERT_TRUE(HITLS_GetPeerCertificate(NULL) == NULL); ASSERT_TRUE(HITLS_GetPeerCertChain(NULL) == NULL); ctx->session = NULL; ASSERT_TRUE(HITLS_GetPeerCertificate(ctx) == NULL); ASSERT_TRUE(HITLS_GetPeerCertChain(ctx) == NULL); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_HITLS_CM_HITLS_Set_and_Get_ErrorCode_API_TC001 * @spec - * @title Cover the input parameter of HITLS_SetChainStore and HITLS_GetChainStore interface * @precon nan * @brief 1. Invoke the HITLS_GetErrorCode interface and leave ctx blank. Expected result 1. 2. Invoke the HITLS_GetErrorCode interface with ctx not empty. Expected result 3. 3. Invoke the HITLS_SetErrorCode interface and leave ctx blank. Expected result 1. 4. Invoke the HITLS_SetErrorCode interface. The value of ctx is not empty. Expected result 2. * @expect 1. Return HITLS_NULL_INPUT 2. Return HITLS_SUCCESS 3. Return errorCode * @prior Level 1 * @auto TRUE @ */ /* BEGIN_CASE */ void UT_HITLS_CM_HITLS_Set_and_Get_ErrorCode_API_TC001(int version) { HitlsInit(); HITLS_Config *tlsConfig = NULL; HITLS_Ctx *ctx = NULL; uint32_t errorCode = 0; tlsConfig = HitlsNewCtx(version); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); HITLS_SetErrorCode(ctx, errorCode); ASSERT_TRUE(HITLS_GetErrorCode(NULL) == HITLS_NULL_INPUT); ASSERT_EQ(HITLS_GetErrorCode(ctx), errorCode); ASSERT_TRUE(HITLS_SetErrorCode(ctx, errorCode) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_SetErrorCode(NULL, errorCode) == HITLS_NULL_INPUT); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_HITLS_CM_SET_GET_ENCRYPTTHENMAC_TC001 * @title Test the HITLS_SetEncryptThenMac and HITLS_GetEncryptThenMac interfaces. * @precon nan * @brief HITLS_SetEncryptThenMac * 1. Transfer an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set encryptThenMacType to an invalid value. Expected result 2. * 3. Transfer a non-empty TLS connection handle and set encryptThenMacType to a valid value. Expected result 3. * HITLS_GetEncryptThenMac * 1. Transfer an empty TLS connection handle. Expected result 1. * 2. Transfer an empty encryptThenMacType pointer. Expected result 1. * 3. Transfer the non-null TLS connection handle information and ensure that the encryptThenMacType pointer is not null. Expected result 3. * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCES and isEncryptThenMac is True * 3. Return HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_HITLS_CM_SET_GET_ENCRYPTTHENMAC_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint32_t encryptThenMacType = 0; ASSERT_TRUE(HITLS_SetEncryptThenMac(ctx, encryptThenMacType) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetEncryptThenMac(ctx, &encryptThenMacType) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetEncryptThenMac(ctx, NULL) == HITLS_NULL_INPUT); encryptThenMacType = 1; ASSERT_TRUE(HITLS_SetEncryptThenMac(ctx, encryptThenMacType) == HITLS_SUCCESS); encryptThenMacType = -1; ASSERT_TRUE(HITLS_SetEncryptThenMac(ctx, encryptThenMacType) == HITLS_SUCCESS); ASSERT_TRUE(config->isEncryptThenMac = true); uint32_t getencryptThenMacType = -1; ASSERT_TRUE(HITLS_GetEncryptThenMac(ctx, &getencryptThenMacType) == HITLS_SUCCESS); ASSERT_TRUE(getencryptThenMacType == true); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /* @ * @test UT_HITLS_CM_HITLS_GetPostHandshakeAuthSupport_TC001 * @title Test the HITLS_GetPostHandshakeAuthSupport interfaces. * @precon nan * @brief 1. Transfer an empty TLS connection handle. Expected result 1. * 2. Transfer a non-empty TLS connection handle and set isSupport to to NULL. Expected result 1. * 3. Transfer a non-empty TLS connection handle and set isSupport to a valid value. Expected result 2. * @expect 1. Return HITLS_NULL_INPUT * 2. Return HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_HITLS_CM_HITLS_GetPostHandshakeAuthSupport_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint32_t isSupport = 0; ASSERT_TRUE(HITLS_GetPostHandshakeAuthSupport(NULL, NULL) == HITLS_NULL_INPUT); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetEncryptThenMac(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetEncryptThenMac(ctx, isSupport) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_sdv_frame_cm_interface.c
C
unknown
172,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. */ /* BEGIN_HEADER */ #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/select.h> #include <sys/time.h> #include <linux/ioctl.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #include <stddef.h> #include <sys/types.h> #include <regex.h> #include "securec.h" #include "bsl_sal.h" #include "sal_net.h" #include "hitls.h" #include "frame_tls.h" #include "cert_callback.h" #include "hitls_config.h" #include "hitls_error.h" #include "bsl_errno.h" #include "bsl_uio.h" #include "frame_io.h" #include "uio_abstraction.h" #include "tls.h" #include "tls_config.h" #include "logger.h" #include "process.h" #include "hs_ctx.h" #include "hlt.h" #include "stub_replace.h" #include "hitls_type.h" #include "frame_link.h" #include "session_type.h" #include "common_func.h" #include "hitls_func.h" #include "hitls_cert_type.h" #include "cert_mgr_ctx.h" #include "parser_frame_msg.h" #include "recv_process.h" #include "simulate_io.h" #include "rec_wrapper.h" #include "cipher_suite.h" #include "alert.h" #include "conn_init.h" #include "pack.h" #include "send_process.h" #include "cert.h" #include "hitls_cert_reg.h" #include "hitls_crypt_type.h" #include "hs.h" #include "hs_state_recv.h" #include "app.h" #include "record.h" #include "rec_conn.h" #include "session.h" #include "frame_msg.h" #include "pack_frame_msg.h" #include "cert_mgr.h" #include "hs_extensions.h" #include "hlt_type.h" #include "sctp_channel.h" #include "hitls_crypt_init.h" #include "crypt_default.h" #include "stub_crypt.h" #include "hitls_crypt.h" #include "security.h" /* END_HEADER */ #define DEFAULT_DESCRIPTION_LEN 128 #define ERROR_HITLS_GROUP 1 #define ERROR_HITLS_SIGNATURE 0xffffu typedef struct { uint16_t version; BSL_UIO_TransportType uioType; HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_Session *clientSession; /* Set the session to the client for session resume. */ } ResumeTestInfo; static HITLS_Config *GetHitlsConfigViaVersion(int ver) { switch (ver) { case TLS1_2: case HITLS_VERSION_TLS12: return HITLS_CFG_NewTLS12Config(); case TLS1_3: case HITLS_VERSION_TLS13: return HITLS_CFG_NewTLS13Config(); case DTLS1_2: case HITLS_VERSION_DTLS12: return HITLS_CFG_NewDTLS12Config(); default: return NULL; } } static int32_t UT_ClientHelloCb(HITLS_Ctx *ctx, int32_t *alert, void *arg) { (void)ctx; (void)alert; return *(int32_t *)arg; } static int32_t UT_CookieGenerateCb(HITLS_Ctx *ctx, uint8_t *cookie, uint32_t *cookie_len) { (void)ctx; (void)cookie; (void)cookie_len; return 0; } static int32_t UT_CookieVerifyCb(HITLS_Ctx *ctx, const uint8_t *cookie, uint32_t cookie_len) { (void)ctx; (void)cookie; (void)cookie_len; return 1; } /** @ * @test UT_TLS_CFG_UPREF_FUNC_TC001 * @spec - * @title Invoke the HITLS_CFG_UpRef interface to change the number of config reference times. * @precon nan * @brief 1. Apply for and initialize config. 2. Invoke the HITLS_CFG_UpRef interface and transfer the config parameter. 3. Check the number of times the config file is referenced. * @expect 1. The application is successful. 2. The invoking is successful. 3. The number of references is 2. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_UPREF_FUNC_TC001() { HitlsInit(); HITLS_Config *config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); ASSERT_TRUE(HITLS_CFG_UpRef(config) == HITLS_SUCCESS); ASSERT_TRUE(config->references.count == 2); HITLS_CFG_FreeConfig(config); ASSERT_TRUE(config->references.count == 1); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_RESUMPTIONONRENEGOSUPPORT_API_TC001 * @Specifications- * @title Test the HITLS_CFG_SetResumptionOnRenegoSupport interface for setting ResumptionOnRenegoSupport. * @preppynan * @brief HITLS_CFG_Setting negotiation support * 1. Transfer empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and support invalid values. Expected result 2 is displayed. * 3. The input configuration information is not empty and the value can be valid. Expected result 3 is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and isResumptionOnRenego is set to true. * 3. HITLS_SUCCES is returned and isResumptionOnRenego is set to true or false. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_RESUMPTIONONRENEGOSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; bool support = -1; ASSERT_TRUE(HITLS_CFG_SetResumptionOnRenegoSupport(config, support) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_SetResumptionOnRenegoSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(config->isResumptionOnRenego == true); support = false; ASSERT_TRUE(HITLS_CFG_SetResumptionOnRenegoSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(config->isResumptionOnRenego == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_NOCLIENTCERTSUPPORT_API_TC001 * @spec - * @title Test the HITLS_CFG_SetNoClientCertSupport and HITLS_CFG_GetNoClientVerifySupport interfaces. * @precon nan * @brief HITLS_CFG_SetNoClientCertSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set support to an invalid value. Expected result 2 is obtained. * 3. Transfer non-empty configuration information and set support to a valid value. Expected result 3 is obtained. * HITLS_CFG_GetNoClientCertSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer an empty isSupport pointer. Expected result 1 is obtained. * 3. Transfer the non-null configuration information and the isSupport pointer is not null. Expected result 3 is * obtained. * @expect 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and config->isSupportNoClientCert is true. * 3. Returns HITLS_SUCCES and config->isSupportNoClientCert is true or false. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_NOCLIENTCERTSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_CFG_SetNoClientCertSupport(config, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetNoClientCertSupport(config, &isSupport) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetNoClientCertSupport(config, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_CFG_SetNoClientCertSupport(config, support) == HITLS_SUCCESS); support = -1; ASSERT_TRUE(HITLS_CFG_SetNoClientCertSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetNoClientCertSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_CFG_SetNoClientCertSupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetNoClientCertSupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_CLIENTVERIFYSUPPORT_API_TC001 * @spec - * @title Test the HITLS_CFG_SetClientVerifySupport and HITLS_CFG_GetClientVerifySupport interfaces. * @precon nan * @brief HITLS_CFG_SetClientVerifySupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set support to an invalid value. Expected result 2 is obtained. * 3. Transfer non-empty configuration information and set support to a valid value. Expected result 3 is obtained. * HITLS_CFG_GetClientVerifySupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer an empty isSupport pointer. Expected result 1 is obtained. * 3. Transfer the non-null configuration information and the isSupport pointer is not null. Expected result 3 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned, and config->isSupportClientVerify is true and isSupportVerifyNone is false. * 3. HITLS_SUCCES is returned, and config->isSupportClientVerify is true or false. isSupportVerifyNone and isSupportVerifyNone are mutually exclusive, but can be false at the same time. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_CLIENTVERIFYSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; bool support = -1; uint8_t isSupport = -1; ASSERT_TRUE(HITLS_CFG_SetClientVerifySupport(config, support) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetClientVerifySupport(config, &isSupport) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetClientVerifySupport(config, NULL) == HITLS_NULL_INPUT); support = true; ASSERT_TRUE(HITLS_CFG_SetClientVerifySupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(config->isSupportVerifyNone == false); support = -1; ASSERT_TRUE(HITLS_CFG_SetClientVerifySupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetClientVerifySupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == true); support = false; ASSERT_TRUE(HITLS_CFG_SetClientVerifySupport(config, support) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetClientVerifySupport(config, &isSupport) == HITLS_SUCCESS); ASSERT_TRUE(isSupport == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_TMPDH_API_TC001 * @spec - * @title Test the HITLS_CFG_SetTmpDh interface. * @precon nan * @brief HITLS_CFG_SetTmpDh * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and leave dhPkey empty. Expected result 1 is obtained. * 3. Transfer non-empty configuration information and set dhPkey to a non-empty value. Expected result 2 is displayed. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_TMPDH_API_TC001(int tlsVersion, int securityBits, int securityLevel) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_CRYPT_Key *dhPkey = NULL; switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } dhPkey = HITLS_CRYPT_GenerateDhKeyBySecbits(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, securityBits); ASSERT_TRUE(HITLS_CFG_SetTmpDh(NULL, dhPkey) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetSecurityLevel(config, securityLevel) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetTmpDh(config, NULL) == HITLS_NULL_INPUT); if (SECURITY_GetSecbits(securityLevel) <= securityBits) { ASSERT_TRUE(HITLS_CFG_SetTmpDh(config, dhPkey) == HITLS_SUCCESS); } else { ASSERT_TRUE(HITLS_CFG_SetTmpDh(config, dhPkey) == HITLS_CRYPT_ERR_DH); } EXIT: if (SECURITY_GetSecbits(securityLevel) > securityBits) { SAL_CRYPT_FreeDhKey(dhPkey); } HITLS_CFG_FreeConfig(config); } /* END_CASE */ int32_t g_securityBits = 0; static HITLS_CRYPT_Key *UT_TmpDhCb(HITLS_Ctx *ctx, int32_t isExport, uint32_t keyLen) { (void)isExport; (void)keyLen; HITLS_CRYPT_Key *dhPkey = NULL; HITLS_Config *config = &ctx->config.tlsConfig; dhPkey = HITLS_CRYPT_GenerateDhKeyBySecbits(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, g_securityBits); return dhPkey; } /* @ * @test UT_TLS_CFG_SET_TMPDHCB_API_TC001 * @title Set tmpdhcallback. The link setup status varies according to the security level. * @precon nan * @brief * 1. Set the RSA certificate and algorithm suite. * 2. Set dh callback and generate dhkey through dhcb. * 3. Set security level to 2, set tmpdh key to 80 bits, and set up a link. * 4. Set security level to 2, set tmpdh key to 112 bits, and set up a link. * 5. Set security level to 1, set tmpdh key to 128 bits, and set up a link. * 6. Set security level to 2, set tmpdh key to 128 bits, and set up a link. * @expect * 1. The setting is successful. * 2. The setting is successful. * 3. The link fails to be set up. * 4. The link is set up successfully. * 5. The link is set up successfully. * 6. The link is set up successfully. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_TMPDHCB_API_TC001(int securityBits, int securityLevel) { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; uint16_t pfsCipherSuites[] = {HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256}; HITLS_Config *clientConfig = HITLS_CFG_NewTLS12Config(); HITLS_Config *serverConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HiTLS_X509_LoadCertAndKey(clientConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, NULL, RSA_SHA256_PRIV_PATH3, NULL) == HITLS_SUCCESS); ASSERT_TRUE(HiTLS_X509_LoadCertAndKey(serverConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, NULL, RSA_SHA256_PRIV_PATH3, NULL) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(clientConfig, pfsCipherSuites, sizeof(pfsCipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(serverConfig, pfsCipherSuites, sizeof(pfsCipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); HITLS_CFG_SetDhAutoSupport(serverConfig, false); g_securityBits = securityBits; ASSERT_TRUE(HITLS_CFG_SetTmpDhCb(serverConfig, UT_TmpDhCb) == HITLS_SUCCESS); FRAME_CertInfo certInfo = {0, 0, 0, 0, 0, 0}; client = FRAME_CreateLinkWithCert(clientConfig, BSL_UIO_TCP, &certInfo); server = FRAME_CreateLinkWithCert(serverConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_TRUE(HITLS_SetSecurityLevel(server->ssl, securityLevel) == HITLS_SUCCESS); if (SECURITY_GetSecbits(securityLevel) > securityBits) { ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_KEY_EXCHANGE), HITLS_SUCCESS); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_MSG_HANDLE_ERR_GET_DH_KEY); } else { ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); } EXIT: HITLS_CFG_FreeConfig(serverConfig); HITLS_CFG_FreeConfig(clientConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_CLIENTHELLOCB_API_TC001 * @title Test the HITLS_CFG_SetClientHelloCb interface. * @precon nan * @brief HITLS_CFG_SetClientHelloCb * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and leave callback empty. Expected result 1 is obtained. * 3. Transfer non-empty configuration information and set callback to a non-empty value. Expected result 2 is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_CLIENTHELLOCB_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; int32_t cbRetVal = 0; ASSERT_TRUE(HITLS_CFG_SetClientHelloCb(config, UT_ClientHelloCb, &cbRetVal) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_SetClientHelloCb(config, NULL, &cbRetVal) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetClientHelloCb(config, UT_ClientHelloCb, &cbRetVal) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_COOKIEGENERATECB_API_TC001 * @title Test the HITLS_CFG_SetCookieGenCb interface. * @precon nan * @brief HITLS_CFG_SetCookieGenCb * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and leave callback empty. Expected result 1 is obtained. * 3. Transfer non-empty configuration information and set callback to a non-empty value. Expected result 2 is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_COOKIEGENERATECB_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; ASSERT_TRUE(HITLS_CFG_SetCookieGenCb(config, UT_CookieGenerateCb) == HITLS_NULL_INPUT); config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(HITLS_CFG_SetCookieGenCb(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetCookieGenCb(config, UT_CookieGenerateCb) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_COOKIEVERIFYCB_API_TC001 * @title Test the HITLS_CFG_SetCookieVerifyCb interface. * @precon nan * @brief HITLS_CFG_SetCookieVerifyCb * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and leave callback empty. Expected result 1 is obtained. * 3. Transfer non-empty configuration information and set callback to a non-empty value. Expected result 2 is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_COOKIEVERIFYCB_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; ASSERT_TRUE(HITLS_CFG_SetCookieVerifyCb(config, UT_CookieVerifyCb) == HITLS_NULL_INPUT); config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(HITLS_CFG_SetCookieVerifyCb(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetCookieVerifyCb(config, UT_CookieVerifyCb) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_VERSION_API_TC001 * @title Test the HITLS_CFG_SetVersion, HITLS_CFG_GetMinVersion, and HITLS_CFG_GetMaxVersion interfaces. * @precon nan * @brief HITLS_CFG_SetVersion * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information, set minVersion to 0, and set maxVersion to a value other than 0. * Expected result 2 is obtained. * 3. Transfer non-empty configuration information, set minVersion to 0, and set maxVersion to 0. Expected result 3 is * obtained. * 4. Transfer non-empty configuration information, set minVersion to 0, and set maxVersion to 0. Expected result 4 is * obtained. * 5. Transfer non-empty configuration information, and set both minVersion and maxVersion to 0. Expected result 5 is * obtained. * 5. Transfer non-empty configuration information, set minVersion to dtls, and set maxVersion to dtls. Expected result 5 * is obtained. * 6. Transfer non-empty configuration information, set minVersion to TLCP, and set maxVersion to TLCP. Expected result 5 * is obtained. * HITLS_CFG_GetMinVersion * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer an empty MinVersion pointer. Expected result 1 is obtained. * 3. Transfer the non-null configuration information and the MinVersion pointer is not null. Expected result 5 is * obtained. * HITLS_CFG_GetMaxVersion * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Pass an empty MaxVersion pointer. Expected result 1 is obtained. * 3. Transfer non-null configuration information and ensure that the MaxVersion pointer is not null. Expected result 5 * is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES and minVersion is HITLS_VERSION_SSL30. * 3. Returns HITLS_SUCCES and maxVersion is HITLS_VERSION_TLS13. * 4. The HITLS_SUCCES table is returned, and the version value is 0, which is cleared. * 5. Returns HITLS_SUCCES with minVersion and maxVersion set to the configured values. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_VERSION_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; HITLS_Config *dtlsConfig = NULL; HITLS_Config *tlcpConfig = NULL; uint16_t minVersion = 0; uint16_t maxVersion = 0; ASSERT_TRUE(HITLS_CFG_SetVersion(config, minVersion, maxVersion) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMinVersion(config, &minVersion) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(config, &maxVersion) == HITLS_NULL_INPUT); config = HITLS_CFG_NewTLSConfig(); dtlsConfig = HITLS_CFG_NewDTLSConfig(); tlcpConfig = HITLS_CFG_NewTLCPConfig(); ASSERT_TRUE(HITLS_CFG_GetMinVersion(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(config, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetVersion(config, 0, 0) == HITLS_SUCCESS); ASSERT_TRUE(config->version == 0); ASSERT_TRUE(HITLS_CFG_SetVersion(config, HITLS_VERSION_TLS12, HITLS_VERSION_TLS13) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMinVersion(config, &minVersion) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(config, &maxVersion) == HITLS_SUCCESS); ASSERT_TRUE(minVersion == HITLS_VERSION_TLS12 && maxVersion == HITLS_VERSION_TLS13); ASSERT_TRUE(HITLS_CFG_SetVersion(config, 0, HITLS_VERSION_TLS13) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMinVersion(config, &minVersion) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(config, &maxVersion) == HITLS_SUCCESS); ASSERT_TRUE(minVersion == HITLS_VERSION_TLS12 && maxVersion == HITLS_VERSION_TLS13); ASSERT_TRUE(HITLS_CFG_SetVersion(config, HITLS_VERSION_TLS12, 0) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMinVersion(config, &minVersion) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(config, &maxVersion) == HITLS_SUCCESS); ASSERT_TRUE(minVersion == HITLS_VERSION_TLS12 && maxVersion == HITLS_VERSION_TLS13); ASSERT_TRUE(HITLS_CFG_SetVersion(dtlsConfig, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMinVersion(dtlsConfig, &minVersion) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(dtlsConfig, &maxVersion) == HITLS_SUCCESS); ASSERT_TRUE(minVersion == HITLS_VERSION_DTLS12 && maxVersion == HITLS_VERSION_DTLS12); ASSERT_TRUE(HITLS_CFG_SetVersion(tlcpConfig, HITLS_VERSION_TLCP_DTLCP11, HITLS_VERSION_TLCP_DTLCP11) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMinVersion(tlcpConfig, &minVersion) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxVersion(tlcpConfig, &maxVersion) == HITLS_SUCCESS); ASSERT_TRUE(minVersion == HITLS_VERSION_TLCP_DTLCP11 && maxVersion == HITLS_VERSION_TLCP_DTLCP11); EXIT: HITLS_CFG_FreeConfig(config); HITLS_CFG_FreeConfig(dtlsConfig); HITLS_CFG_FreeConfig(tlcpConfig); } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_HASHID_API_TC001 * @title Test the HITLS_CFG_GetHashId interface. * @precon nan * @brief * 1. Input an empty cipher suite. Expected result 1 is obtained. * 2. Transfer an empty hashId. Expected result 1 is obtained. * 3. Import the HITLS_RSA_WITH_AES_128_CBC_SHA cipher suite and set hashAlg to HITLS_HASH_BUTT. Expected result 2 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCESS is returned and HashId is HITLS_HASH_SHA1. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_HASHID_API_TC001(void) { const HITLS_Cipher *cipher = NULL; HITLS_HashAlgo hashId = HITLS_HASH_BUTT; ASSERT_TRUE(HITLS_CFG_GetHashId(cipher, &hashId) == HITLS_NULL_INPUT); const uint16_t cipherID = HITLS_RSA_WITH_AES_128_CBC_SHA; cipher = HITLS_CFG_GetCipherByID(cipherID); ASSERT_TRUE(HITLS_CFG_GetHashId(cipher, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetHashId(cipher, &hashId) == HITLS_SUCCESS); ASSERT_TRUE(hashId == HITLS_HASH_SHA1); EXIT: return; } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_MACID_API_TC001 * @title Test the HITLS_CFG_GetMacId interface. * @precon nan * @brief * 1. Input an empty cipher suite. Expected result 1 is obtained. * 2. Input an empty macAlg. Expected result 1 * 3. Input the HITLS_RSA_WITH_AES_128_CBC_SHA cipher suite and set macAlg to HITLS_MAC_BUTT. Expected result 2 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCESS and macAlg is HITLS_MAC_1. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_MACID_API_TC001(void) { const HITLS_Cipher *cipher = NULL; HITLS_MacAlgo macAlg = HITLS_MAC_BUTT; ASSERT_TRUE(HITLS_CFG_GetMacId(cipher, &macAlg) == HITLS_NULL_INPUT); const uint16_t cipherID = HITLS_RSA_WITH_AES_128_CBC_SHA; cipher = HITLS_CFG_GetCipherByID(cipherID); ASSERT_TRUE(HITLS_CFG_GetMacId(cipher, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMacId(cipher, &macAlg) == HITLS_SUCCESS); ASSERT_TRUE(macAlg == HITLS_MAC_1); EXIT: return; } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_KEYEXCHID_API_TC001 * @title Test the HITLS_CFG_GetKeyExchId interface. * @precon nan * @brief * 1. Input an empty cipher suite. Expected result 1 is obtained. * 2. Input null kxAlg. Expected result 1 * 3. Input the HITLS_RSA_WITH_AES_128_CBC_SHA cipher suite and set kxAlg to HITLS_KEY_EXCH_BUTT. Expected result 2 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCESS and kxAlg is HITLS_KEY_EXCH_RSA. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_KEYEXCHID_API_TC001(void) { const HITLS_Cipher *cipher = NULL; HITLS_KeyExchAlgo kxAlg = HITLS_KEY_EXCH_BUTT; ASSERT_TRUE(HITLS_CFG_GetKeyExchId(cipher, &kxAlg) == HITLS_NULL_INPUT); const uint16_t cipherID = HITLS_RSA_WITH_AES_128_CBC_SHA; cipher = HITLS_CFG_GetCipherByID(cipherID); ASSERT_TRUE(HITLS_CFG_GetKeyExchId(cipher, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetKeyExchId(cipher, &kxAlg) == HITLS_SUCCESS); ASSERT_TRUE(kxAlg == HITLS_KEY_EXCH_RSA); EXIT: return; } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_CIPHERSUITESTDNAME_API_TC001 * @title Test the HITLS_CFG_GetCipherSuiteStdName interface. * @precon nan * @brief * 1. Input an empty cipher suite. Expected result 1 is obtained. * 2.Import the HITLS_RSA_WITH_AES_128_CBC_SHA cipher suite. Expected result 2 is obtained. * @expect * 1. Return "(NONE)" * 2. Return "TLS_RSA_WITH_AES_128_CBC_SHA256" @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_CIPHERSUITESTDNAME_API_TC001(void) { const HITLS_Cipher *cipher = NULL; ASSERT_TRUE(strcmp((char *)HITLS_CFG_GetCipherSuiteStdName(cipher),"(NONE)") == 0); const uint16_t cipherID = HITLS_RSA_WITH_AES_128_CBC_SHA; cipher = HITLS_CFG_GetCipherByID(cipherID); ASSERT_TRUE(strcmp((char *)HITLS_CFG_GetCipherSuiteStdName(cipher),"TLS_RSA_WITH_AES_128_CBC_SHA") == 0); EXIT: return; } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_DESCRIPTION_API_TC001 * @title Test the HITLS_CFG_GetDescription interface. * @precon nan * @brief * 1. Input an empty cipher suite. Expected result 1 is obtained. * 2. Input an empty buff. Expected result 1 is obtained. * 3. Transfer a buff whose length is less than the length of CIPHERSUITE_DESCRIPTION_MAXLEN. Expected result 1 is * obtained. * 4. Transfer the abnormal algorithm name cipher suite. Expected result 2 is obtained. * 5. Import the HITLS_RSA_WITH_AES_128_CBC_SHA cipher suite whose buff size is DEFAULT_DESCRIPTION_LEN. Expected result * 3 is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_CONFIG_INVALID_LENGTH. * 3. Returns HITLS_SUCCESS, and buff is Description. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_DESCRIPTION_API_TC001(void) { const HITLS_Cipher *cipher = NULL; char buff[DEFAULT_DESCRIPTION_LEN] = {0}; ASSERT_TRUE(HITLS_CFG_GetDescription(cipher, (uint8_t *)buff, sizeof(buff)) == HITLS_NULL_INPUT); const uint16_t cipherID = HITLS_RSA_WITH_AES_128_CBC_SHA; cipher = HITLS_CFG_GetCipherByID(cipherID); ASSERT_TRUE(HITLS_CFG_GetDescription(cipher, NULL, sizeof(buff)) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetDescription(cipher, (uint8_t *)buff, 0) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetDescription(cipher, (uint8_t *)buff, sizeof(buff)) == HITLS_SUCCESS); HITLS_Cipher *newCipher = (HITLS_Cipher *)malloc(sizeof(HITLS_Cipher)); memcpy(newCipher, cipher, sizeof(HITLS_Cipher)); newCipher->name = "************************************************************************************************************"; ASSERT_TRUE(HITLS_CFG_GetDescription(newCipher, (uint8_t *)buff, sizeof(buff)) == HITLS_CONFIG_INVALID_LENGTH); EXIT: free(newCipher); } /* END_CASE */ /** @ * @test UT_TLS_CFG_CIPHER_ISAEAD_API_TC001 * @title Test the HITLS_CIPHER_IsAead interface. * @precon nan * @brief * 1. Input an empty cipher suite. Expected result 1 is obtained. * 2. Import the HITLS_RSA_WITH_AES_128_GCM_SHA256 cipher suite. Expected result 2 is obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCESS and isAead is true. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_CIPHER_ISAEAD_API_TC001(void) { const HITLS_Cipher *cipher = NULL; uint8_t isAead = false; ASSERT_TRUE(HITLS_CIPHER_IsAead(cipher, &isAead) == HITLS_NULL_INPUT); const uint16_t cipherID = HITLS_RSA_WITH_AES_128_GCM_SHA256; cipher = HITLS_CFG_GetCipherByID(cipherID); ASSERT_TRUE(HITLS_CIPHER_IsAead(cipher, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CIPHER_IsAead(cipher, &isAead) == HITLS_SUCCESS); ASSERT_TRUE(isAead == true); EXIT: return; } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_VERSIONSUPPORT_API_TC001 * @spec - * @title Test the HITLS_CFG_SetVersionSupport and HITLS_CFG_GetVersionSupport interfaces. * @precon nan * @brief HITLS_CFG_SetVersionSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set version to an invalid value. Expected result 2 is obtained. * 3. Transfer non-empty configuration information and set version to a valid value. Expected result 3 is obtained. * HITLS_CFG_GetVersionSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Pass the null version pointer. Expected result 1 is obtained. * 3. Transfer non-null configuration information and ensure that the version pointer is not null. Expected result 4 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned, and invalid values in config are filtered out. * 3. HITLS_SUCCES is returned and config is the expected value. * 4. The HITLS_SUCCES parameter is returned, and the version parameter is set to the value recorded in the config file. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_VERSIONSUPPORT_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; uint32_t version = 0; ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config, version) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetVersionSupport(config, &version) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetVersionSupport(config, NULL) == HITLS_NULL_INPUT); version = (TLS13_VERSION_BIT << 1) | TLS13_VERSION_BIT | TLS12_VERSION_BIT; ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); version = TLS13_VERSION_BIT | TLS12_VERSION_BIT; ASSERT_TRUE(HITLS_CFG_SetVersionSupport(config, version) == HITLS_SUCCESS); ASSERT_TRUE(config->minVersion == HITLS_VERSION_TLS12 && config->maxVersion == HITLS_VERSION_TLS13); uint32_t getversion = 0; ASSERT_TRUE(HITLS_CFG_GetVersionSupport(config, &getversion) == HITLS_SUCCESS); ASSERT_TRUE(getversion == config->version); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_QUIETSHUTDOWN_API_TC001 * @title Test the HITLS_CFG_SetQuietShutdown and HITLS_CFG_GetQuietShutdown interfaces. * @precon nan * @brief HITLS_CFG_SetQuietShutdown * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set mode to an invalid value. Expected result 2 is obtained. * 3. Transfer non-empty configuration information and set mode to a valid value. Expected result 3 is obtained. * HITLS_CFG_GetQuietShutdown * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer a null mode pointer. Expected result 1 is obtained. * 3. Transfer non-null configuration information and ensure that the mode pointer is not null. Expected result 3 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_CONFIG_INVALID_SET * 3. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_QUIETSHUTDOWN_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; int32_t mode = 0; ASSERT_TRUE(HITLS_CFG_SetQuietShutdown(config, mode) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetQuietShutdown(config, &mode) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetQuietShutdown(config, NULL) == HITLS_NULL_INPUT); mode = 1; ASSERT_TRUE(HITLS_CFG_SetQuietShutdown(config, mode) == HITLS_SUCCESS); mode = 2; ASSERT_TRUE(HITLS_CFG_SetQuietShutdown(config, mode) == HITLS_CONFIG_INVALID_SET); int32_t getMode = -1; ASSERT_TRUE(HITLS_CFG_GetQuietShutdown(config, &getMode) == HITLS_SUCCESS); ASSERT_TRUE(getMode == config->isQuietShutdown); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_CIPHERSERVERPREFERENCE_API_TC001 * @title Test the HITLS_CFG_SetCipherServerPreference and HITLS_CFG_GetCipherServerPreference interfaces. * @precon nan * @brief HITLS_CFG_SetCipherServerPreference * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set isSupport to an invalid value. Expected result 2 is obtained. * 3. Transfer a non-empty configuration information and set isSupport to a valid value. Expected result 3 is obtained. * HITLS_CFG_GetCipherServerPreference * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer an empty isSupport pointer. Expected result 1 is obtained. * 3. Transfer the non-null configuration information and the isSupport pointer is not null. Expected result 3 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and config->isSupportServerPreference is set to true. * 3. Returns HITLS_SUCCES, and config->isSupportServerPreference is true or false. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_CIPHERSERVERPREFERENCE_API_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; bool isSupport = false; bool getIsSupport = false; ASSERT_TRUE(HITLS_CFG_SetCipherServerPreference(config, isSupport) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetCipherServerPreference(config, &getIsSupport) == HITLS_NULL_INPUT); switch (tlsVersion) { case HITLS_VERSION_TLS12: config = HITLS_CFG_NewTLS12Config(); break; case HITLS_VERSION_TLS13: config = HITLS_CFG_NewTLS13Config(); break; default: config = NULL; break; } ASSERT_TRUE(HITLS_CFG_GetCipherServerPreference(config, NULL) == HITLS_NULL_INPUT); isSupport = true; ASSERT_TRUE(HITLS_CFG_SetCipherServerPreference(config, isSupport) == HITLS_SUCCESS); isSupport = 2; ASSERT_TRUE(HITLS_CFG_SetCipherServerPreference(config, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(config->isSupportServerPreference = true); isSupport = false; ASSERT_TRUE(HITLS_CFG_SetCipherServerPreference(config, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetCipherServerPreference(config, &getIsSupport) == HITLS_SUCCESS); ASSERT_TRUE(getIsSupport == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_HELLO_VERIFY_REQ_API_TC001 * @title Test the HITLS_CFG_SetDtlsCookieExchangeSupport and HITLS_CFG_GetDtlsCookieExchangeSupport interfaces. * @precon nan * @brief HITLS_CFG_SetDtlsCookieExchangeSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer non-empty configuration information and set isSupport to an invalid value. Expected result 2 is obtained. * 3. Transfer a non-empty configuration information and set isSupport to a valid value. Expected result 3 is obtained. * HITLS_CFG_GetDtlsCookieExchangeSupport * 1. Import empty configuration information. Expected result 1 is obtained. * 2. Transfer an empty isSupport pointer. Expected result 1 is obtained. * 3. Transfer the non-null configuration information and the isSupport pointer is not null. Expected result 3 is * obtained. * @expect * 1. Returns HITLS_NULL_INPUT * 2. HITLS_SUCCES is returned and config->isSupportDtlsCookieExchange is set to true. * 3. Returns HITLS_SUCCES, and config->isSupportDtlsCookieExchange is true or false. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_HELLO_VERIFY_REQ_API_TC001(void) { FRAME_Init(); HITLS_Config *config = NULL; bool isSupport = false; bool getIsSupport = false; ASSERT_TRUE(HITLS_CFG_SetDtlsCookieExchangeSupport(config, isSupport) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetDtlsCookieExchangeSupport(config, &getIsSupport) == HITLS_NULL_INPUT); config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(HITLS_CFG_GetDtlsCookieExchangeSupport(config, NULL) == HITLS_NULL_INPUT); isSupport = true; ASSERT_TRUE(HITLS_CFG_SetDtlsCookieExchangeSupport(config, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(config->isSupportDtlsCookieExchange = true); isSupport = false; ASSERT_TRUE(HITLS_CFG_SetDtlsCookieExchangeSupport(config, isSupport) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetDtlsCookieExchangeSupport(config, &getIsSupport) == HITLS_SUCCESS); ASSERT_TRUE(getIsSupport == false); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_RENEGOTIATIONSUPPORT_FUNC_TC001 * @title Test the function of supporting the renegotiation function by setting the HITLS_CFG_SetRenegotiationSupport and * obtaining the function of supporting the renegotiation function by the HITLS_CFG_GetRenegotiationSupport. * @precon nan * @brief 1. Call HITLS_CFG_SetRenegotiationSupport to disable renegotiation. Expected result 1 is obtained. * 2. Invoke the HITLS_CFG_GetRenegotiationSupport interface to obtain the configured value. (Expected result * 2) * 3. Invoke the HITLS_SetRenegotiationSupport interface to support renegotiation. Expected result 3 is * obtained. * 4. Invoke the HITLS_GetRenegotiationSupport interface to obtain the configured value. Expected result 4 is * obtained. * 5. Establish a connection. and check whether the value of isSecureRenegotiation in the * negotiation information is true. Expected result 5 is obtained. * 6. Perform renegotiation. Expected result 6 is obtained. * @expect 1. Setting succeeded. * 2. The interface returns false. * 3. The setting is successful. * 4. The interface returns true. * 5. The value of isSecureRenegotiation is true. * 6. The renegotiation succeeds. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_RENEGOTIATIONSUPPORT_FUNC_TC001() { FRAME_Init(); FRAME_LinkObj *clientRes; FRAME_LinkObj *serverRes; HITLS_Config *config = NULL; uint8_t supportrenegotiation; config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_CFG_SetRenegotiationSupport(config, false); HITLS_CFG_GetRenegotiationSupport(config, &supportrenegotiation); ASSERT_TRUE(supportrenegotiation == false); clientRes = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(clientRes != NULL); serverRes = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(serverRes != NULL); HITLS_SetRenegotiationSupport(clientRes->ssl, true); HITLS_SetRenegotiationSupport(serverRes->ssl, true); HITLS_GetRenegotiationSupport(clientRes->ssl, &supportrenegotiation); ASSERT_TRUE(supportrenegotiation == true); FRAME_CreateConnection(clientRes, serverRes, true, HS_STATE_BUTT); ASSERT_TRUE(clientRes->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(serverRes->ssl->state == CM_STATE_TRANSPORTING); ASSERT_TRUE(HITLS_Renegotiate(serverRes->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(clientRes->ssl) == HITLS_SUCCESS); ASSERT_TRUE(FRAME_CreateRenegotiationState(clientRes, serverRes, true, HS_STATE_BUTT) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(clientRes); FRAME_FreeLink(serverRes); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_ECPOINTFORMATS_FUNC_TC001 * @title Set the normal dot format value. * @precon nan * @brief 1. Set pointFormats to HITLS_POINT_FORMAT_UNCOMPRESSED and invoke the HITLS_CFG_SetEcPointFormats interface. * Expected result 1 is obtained. * 2. Set pointFormats to HITLS_POINT_FORMAT_BUTT and invoke the HITLS_CFG_SetEcPointFormats interface. * (Expected result 2) * 3. Use config to generate ctx, due to the result 3 * 4. Set pointFormats to HITLS_POINT_FORMAT_UNCOMPRESSED again and generate ctx again. Expected result 4 is * obtained. Set pointFormats to HITLS_POINT_FORMAT_UNCOMPRESSED and invoke the HITLS_SetEcPointFormats * interface. (Expected result 2) * 5. Set pointFormats to HITLS_POINT_FORMAT_UNCOMPRESSED and invoke the HITLS_SetEcPointFormats interface. * Expected result 2 is obtained. * @expect 1. Interface return value, HITLS_SUCCESS * 2. Interface return value: HITLS_SUCCESS * 3. Failed to generate the file. * 4. The file is generated successfully. * 5. The setting is successful. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_ECPOINTFORMATS_FUNC_TC001(int version) { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *Config = NULL; HITLS_Ctx *ctx = NULL; Config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(Config != NULL); const uint8_t pointFormats[] = {HITLS_POINT_FORMAT_UNCOMPRESSED}; uint32_t pointFormatsSize = sizeof(pointFormats) / sizeof(uint8_t); ASSERT_TRUE(HITLS_CFG_SetEcPointFormats(Config, pointFormats, pointFormatsSize) == HITLS_SUCCESS); const uint8_t pointFormats2[] = {HITLS_POINT_FORMAT_BUTT}; uint32_t pointFormatsSize2 = sizeof(pointFormats2) / sizeof(uint8_t); ASSERT_TRUE(HITLS_CFG_SetEcPointFormats(Config, pointFormats2, pointFormatsSize2) == HITLS_SUCCESS); ctx = HITLS_New(Config); if(version == TLS1_2){ ASSERT_TRUE(ctx == NULL); } HITLS_Free(ctx); ASSERT_TRUE(HITLS_CFG_SetEcPointFormats(Config, pointFormats, pointFormatsSize) == HITLS_SUCCESS); ctx = HITLS_New(Config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_SetEcPointFormats(ctx, pointFormats, pointFormatsSize) == HITLS_SUCCESS); client = FRAME_CreateLink(Config, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(Config, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(Config); HITLS_Free(ctx); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ typedef struct { HITLS_Config *config; FRAME_LinkObj *client; FRAME_LinkObj *server; HITLS_HandshakeState state; bool isClient; bool isSupportExtendMasterSecret; bool isSupportClientVerify; bool isSupportNoClientCert; bool isSupportRenegotiation; bool isSupportSessionTicket; bool needStopBeforeRecvCCS; } HandshakeTestInfo; /** @ * @test UT_TLS_CFG_SET_GROUPS_FUNC_TC001 * @title Sets the elliptic curve that does not exist. * @precon nan * @brief 1. Set group to 0x0001 and invoke the HITLS_CFG_SetGroups interface. Expected result 1 is obtained. * 2. Establish a connection. Check whether the group value in the client hello message sent by the client is * 0x0001.Expected result 2 is obtained. * 3. Establish a connection and check whether the connection is successfully established. (Expected result 3) * @expect 1. Interface HITLS_SUCCESS * 2. The value of group in the client hello message is 0x0001. * 3. connection establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GROUPS_FUNC_TC001(int version) { FRAME_Init(); HandshakeTestInfo testInfo = {0}; uint16_t group[] = {ERROR_HITLS_GROUP}; uint32_t grouplength = sizeof(group) / sizeof(uint16_t); testInfo.isClient = false; testInfo.config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(testInfo.config != NULL); ASSERT_TRUE(HITLS_CFG_SetGroups(testInfo.config, group, grouplength) == HITLS_SUCCESS); if (version == TLS1_2) { uint16_t cipherSuite[] = {HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}; HITLS_CFG_SetCipherSuites(testInfo.config, cipherSuite, sizeof(cipherSuite) / sizeof(uint16_t)); } FRAME_CertInfo certInfo = { "rsa_sha/ca-3072.der:rsa_sha/inter-3072.der", "rsa_sha/inter-3072.der", "rsa_sha/end-sha256.der", NULL, "rsa_sha/end-sha256.key.der", NULL, }; testInfo.client = FRAME_CreateLinkWithCert(testInfo.config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(testInfo.client != NULL); testInfo.server = FRAME_CreateLinkWithCert(testInfo.config, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(testInfo.server != NULL); if (version == TLS1_2) { ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, HS_STATE_BUTT), HITLS_MSG_HANDLE_CIPHER_SUITE_ERR); } else { ASSERT_EQ(FRAME_CreateConnection(testInfo.client, testInfo.server, testInfo.isClient, HS_STATE_BUTT), HITLS_MSG_HANDLE_ILLEGAL_SELECTED_GROUP); } EXIT: HITLS_CFG_FreeConfig(testInfo.config); FRAME_FreeLink(testInfo.client); FRAME_FreeLink(testInfo.server); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_SIGNATURE_FUNC_TC001 * @title Set a nonexistent signature algorithm. * @precon nan * @brief * 1. Set Signature to 0xffff and call the HITLS_CFG_SetSignature interface. (Expected result 1) * @expect * 1. Interface return value: HITLS_CONFIG_INVALID_LENGTH @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_SIGNATURE_FUNC_TC001(int version) { FRAME_Init(); FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_Config *config = NULL; config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(config != NULL); uint16_t signAlgs[] = {ERROR_HITLS_SIGNATURE}; ASSERT_TRUE(HITLS_CFG_SetSignature(config, signAlgs, sizeof(signAlgs) / sizeof(uint16_t)) == HITLS_SUCCESS); client = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(client == NULL); server = FRAME_CreateLink(config, BSL_UIO_TCP); ASSERT_TRUE(server == NULL); EXIT: HITLS_CFG_FreeConfig(config); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ void ExampleInfoCallback(const HITLS_Ctx *ctx, int32_t eventType, int32_t value) { (void)ctx; (void)eventType; (void)value; } #define MSG_CB_PRINT_LEN 500 void msg_callback(int32_t writePoint, int32_t tlsVersion, int32_t contentType, const void *msg, uint32_t msgLen, HITLS_Ctx *ctx, void *arg) { (void)writePoint; (void)tlsVersion; (void)contentType; (void)msg; (void)msgLen; (void)ctx; (void)arg; } /* @ * @test UT_TLS_CFG_InfoCb_API_TC001 * @title InfoCb Interface Parameter Test * @precon nan * @brief 1. Use the HITLS_CFG_GetInfoCb without HITLS_CFG_SetInfoCb. Expected result 1 is obtained. 2. Use the HITLS_CFG_SetInfoCb interface to set callback. Expected result 2 3. Use the HITLS_CFG_GetInfoCb . Expected result 3 4. Use the HITLS_CFG_GetInfoCb with the parameter is NULL . Expected result 4 * @expect 1. Return the NULL. 2. Return the HITLS_SUCCESS 3. Return value is not NULL. 4. Return the NULL. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_InfoCb_API_TC001(void) { FRAME_Init(); HITLS_Config *config = HITLS_CFG_NewDTLS12Config(); ASSERT_TRUE(config != NULL); HITLS_InfoCb infoCallBack = HITLS_CFG_GetInfoCb(config); ASSERT_TRUE(infoCallBack == NULL); int32_t ret = HITLS_CFG_SetInfoCb(config, ExampleInfoCallback); ASSERT_TRUE(ret == HITLS_SUCCESS); infoCallBack = HITLS_CFG_GetInfoCb(config); ASSERT_TRUE(infoCallBack != NULL); infoCallBack = HITLS_CFG_GetInfoCb(NULL); ASSERT_TRUE(infoCallBack == NULL); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SetMsgCb_API_TC001 * @title HITLS_CFG_SetMsgCb Interface Parameter Test * @precon nan * @brief 1. Set config to NULL. Expected result 1 is obtained. 2. Invoke the HITLS_CFG_SetMsgCb interface to set callback. (Expected result 2) * @expect 1. Return the HITLS_NULL_INPUT message. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SetMsgCb_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); ASSERT_EQ(HITLS_CFG_SetMsgCb(NULL, msg_callback), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_CFG_SetMsgCb(tlsConfig, msg_callback), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SetMsgCbArg_API_TC001 * @title HITLS_CFG_SetMsgCbArg Interface Parameter Test * @precon nan * @brief 1. Set config to NULL. Expected result 1 is obtained. 2. Use the HITLS_CFG_SetMsgCbArg interface to set Arg. Expected result 2 is obtained. * @expect 1. The HITLS_NULL_INPUT message is returned. 2. Return the HITLS_SUCCESS @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SetMsgCbArg_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig; tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); ASSERT_EQ(HITLS_CFG_SetMsgCbArg(NULL, msg_callback), HITLS_NULL_INPUT); ASSERT_EQ(HITLS_CFG_SetMsgCbArg(tlsConfig, msg_callback), HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(tlsConfig); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SETTMPDH_FUNC_TC001 * @title Set tmpdhkey. The link setup status varies according to the security level. * @precon nan * @brief * 1. Set the RSA certificate and algorithm suite. * 2. Set the dh key to not follow the certificate, and set the tmpdh key with 80 security bits. * 3. Set the security level to 0 and set up a link. * 4. Set the security level to 2 and set up a link. * @expect * 1. The setting is successful. * 2. The setting is successful. * 3. The link is set up successfully. * 4. The link fails to be set up. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SETTMPDH_FUNC_TC001(int level) { (void)level; FRAME_Init(); HITLS_Config *clientConfig = NULL; HITLS_Config *serverConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; HITLS_CRYPT_Key *key = NULL; uint16_t pfsCipherSuites[] = {HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256}; clientConfig = HITLS_CFG_NewTLS12Config(); serverConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HiTLS_X509_LoadCertAndKey(clientConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, NULL, RSA_SHA256_PRIV_PATH3,NULL) == HITLS_SUCCESS); ASSERT_TRUE(HiTLS_X509_LoadCertAndKey(serverConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, NULL, RSA_SHA256_PRIV_PATH3,NULL) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(clientConfig, pfsCipherSuites, sizeof(pfsCipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(serverConfig, pfsCipherSuites, sizeof(pfsCipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); HITLS_CFG_SetSecurityLevel(serverConfig, level); HITLS_CFG_SetSecurityLevel(clientConfig, level); HITLS_CFG_SetDhAutoSupport(serverConfig, false); int32_t secBits = 80; key = HITLS_CRYPT_GenerateDhKeyBySecbits(LIBCTX_FROM_CONFIG(serverConfig), ATTRIBUTE_FROM_CONFIG(serverConfig), serverConfig, secBits); HITLS_CFG_SetTmpDh(serverConfig, key); FRAME_CertInfo certInfo = {0, 0, 0, 0, 0, 0}; client = FRAME_CreateLinkWithCert(clientConfig, BSL_UIO_TCP, &certInfo); server = FRAME_CreateLinkWithCert(serverConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); if (level > 1) { ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_KEY_EXCHANGE), HITLS_SUCCESS); FRAME_TrasferMsgBetweenLink(server, client); HITLS_Connect(client->ssl); ASSERT_EQ(HITLS_Accept(server->ssl) , HITLS_MSG_HANDLE_ERR_GET_DH_KEY); } else { ASSERT_EQ(FRAME_CreateConnection(client, server, false, HS_STATE_BUTT), HITLS_SUCCESS); } EXIT: if (SECURITY_GetSecbits(level) > secBits) { SAL_CRYPT_FreeDhKey(key); } HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /* @ * @test UT_TLS_CFG_SET_POSTHANDSHAKEAUTHSUPPORT_API_TC001 * * @title Test the HITLS_SetPostHandshakeAuthSupport interface. * * @brief * 1. The default value of the TLS connection handle isSupportPostHandshakeAuth is fasle. Expected result 1。 * 2. Run the HITLS_SetPostHandshakeAuthSupport command to set a handle. The value of isSupportPostHandshakeAuth is true. * Expected result 2. * @expect * 1. isSupportPostHandshakeAuth is false. * 2. isSupportPostHandshakeAuth is true. @*/ /* BEGIN_CASE */ void UT_TLS_CFG_SET_POSTHANDSHAKEAUTHSUPPORT_API_TC001(int tlsVersion) { HitlsInit(); HITLS_Config *tlsConfig = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(tlsConfig != NULL); HITLS_Ctx *ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(ctx->config.tlsConfig.isSupportPostHandshakeAuth == false); int ret = HITLS_SetPostHandshakeAuthSupport(ctx, true); ASSERT_TRUE(ret == HITLS_SUCCESS); ASSERT_TRUE(ctx->config.tlsConfig.isSupportPostHandshakeAuth == true); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CFG_GET_SECURE_RENEGOTIATIONSUPPORET_FUNC_TC001 * @title HITLS_GetSecureRenegotationSupport The client does not support security renegotiation, * but the server supports security renegotiation. Obtains whether security renegotiation is supported. * @precon nan * @brief HITLS_GetSecureRenegotationSupport * 1. Transfer an empty TLS connection handle. Expected result 1. * 2. Transfer the non-empty TLS connection handle information and leave isSecureRenegotiation blank. Expected result 1. * 3. Transfer the non-empty TLS connection handle information. The isSecureRenegotiation parameter is not empty. * Expected result 2. * @expect * 1. Returns HITLS_NULL_INPUT * 2. Returns HITLS_SUCCES @ */ /* BEGIN_CASE */ void UT_TLS_CFG_GET_SECURE_RENEGOTIATIONSUPPORET_API_TC001(void) { HitlsInit(); HITLS_Config *config = NULL; HITLS_Ctx *ctx = NULL; uint8_t isSecureRenegotiation = 0; ASSERT_TRUE(HITLS_GetSecureRenegotiationSupport(NULL, &isSecureRenegotiation) == HITLS_NULL_INPUT); config = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config != NULL); ctx = HITLS_New(config); ASSERT_TRUE(ctx != NULL); ASSERT_TRUE(HITLS_GetSecureRenegotiationSupport(ctx, NULL) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetSecureRenegotiationSupport(ctx, &isSecureRenegotiation) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); HITLS_Free(ctx); } /* END_CASE */ /** @ * @test UT_TLS_CFG_SET_GET_DHAUTOSUPPORT_FUNC_TC001 * @title Test the HITLS_SetDhAutoSupport and HITLS_CFG_GetDhAutoSupport interfaces. * @precon nan * @brief * 1. Invoke the HITLS_CFG_SetDhAutoSupport interface to set the parameter to false. Expected result 1 is obtained. * 2. Establish a connection. Expected result 2 is obtained. * @expect * 1. The setting is successful. * 2. connection establishment fails. @ */ /* BEGIN_CASE */ void UT_TLS_CFG_SET_GET_DHAUTOSUPPORT_FUNC_TC001(void) { FRAME_Init(); HITLS_Config *clientConfig = NULL; HITLS_Config *serverConfig = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; uint16_t pfsCipherSuites[] = {HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256}; clientConfig = HITLS_CFG_NewTLS12Config(); serverConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(clientConfig != NULL); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(HiTLS_X509_LoadCertAndKey(clientConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, NULL, RSA_SHA256_PRIV_PATH3,NULL) == HITLS_SUCCESS); ASSERT_TRUE(HiTLS_X509_LoadCertAndKey(serverConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, NULL, RSA_SHA256_PRIV_PATH3,NULL) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(clientConfig, pfsCipherSuites, sizeof(pfsCipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_SetCipherSuites(serverConfig, pfsCipherSuites, sizeof(pfsCipherSuites) / sizeof(uint16_t)) == HITLS_SUCCESS); HITLS_CFG_SetDhAutoSupport(serverConfig, false); FRAME_CertInfo certInfo = {0, 0, 0, 0, 0, 0}; client = FRAME_CreateLinkWithCert(clientConfig, BSL_UIO_TCP, &certInfo); server = FRAME_CreateLinkWithCert(serverConfig, BSL_UIO_TCP, &certInfo); ASSERT_TRUE(client != NULL); ASSERT_TRUE(server != NULL); ASSERT_EQ(FRAME_CreateConnection(client, server, false, TRY_SEND_SERVER_KEY_EXCHANGE), HITLS_SUCCESS); FRAME_TrasferMsgBetweenLink(server, client); HITLS_Connect(client->ssl); ASSERT_EQ(HITLS_Accept(server->ssl), HITLS_MSG_HANDLE_ERR_GET_DH_KEY); EXIT: HITLS_CFG_FreeConfig(clientConfig); HITLS_CFG_FreeConfig(serverConfig); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_sdv_frame_config_interface.c
C
unknown
60,914
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdlib.h> #include <string.h> #include <stddef.h> #include <stdio.h> #include <linux/limits.h> #include <unistd.h> #include <stdbool.h> #include "hitls_error.h" #include "hitls_cert.h" #include "hitls.h" #include "hitls_func.h" #include "securec.h" #include "cert_method.h" #include "cert_mgr.h" #include "cert_mgr_ctx.h" #include "frame_tls.h" #include "frame_link.h" #include "frame_io.h" #include "hlt_type.h" #include "process.h" #include "hlt.h" #include "session.h" #include "bsl_sal.h" #include "alert.h" #include "stub_replace.h" #include "cert_callback.h" #include "crypt_eal_rand.h" #include "hitls_crypt_reg.h" #include "hitls_crypt_init.h" #include "logger.h" #include "uio_base.h" #include "hitls_cert_type.h" #include "hitls_type.h" #include "hitls_cert_reg.h" #include "hitls_config.h" #include "hitls_cert_init.h" #include "bsl_log.h" #include "bsl_err.h" #include "tls_config.h" #include "tls.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "bsl_uio.h" #include "bsl_obj.h" #include "bsl_errno.h" #include "hitls_x509_adapt.h" /* END_HEADER */ #define BUF_MAX_SIZE 4096 int32_t g_uiPort = 18886; #define DEFAULT_CERT_PATH "../../testcode/testdata/tls/certificate/der/" #define CERT_PATH_LEN 120 #define SUCCESS (0) #define ERROR (1) #define MAX_BUFFER (8192) #define READ_BUF_LEN_18K (18 * 1024) #define READ_DATA_18432 18432 #define PASSWDLEN (10) #define CERT_PATH_BUFFER (100) #define RSA_ROOT_CERT_DER "rsa_sha/ca-3072.der" #define RSA_CA_CERT_DER "rsa_sha/inter-3072.der" #define RSA_EE_CERT_DER "rsa_sha/end-sha1.der" #define RSA_PRIV_KEY_DER "rsa_sha/end-sha1.key.der" #define RSA_EE_CERT_DER "rsa_sha/end-sha1.der" #define RSA_PRIV_KEY_DER "rsa_sha/end-sha1.key.der" #define RSA_ROOT_CERT2_DER "rsa_sha256/ca.der" #define RSA_CA_CERT2_DER "rsa_sha256/inter.der" #define RSA_EE_CERT2_DER "rsa_sha256/server.der" #define RSA_PRIV_KEY2_DER "rsa_sha256/server.key.der" #define ECDSA_ROOT_CERT_DER "ecdsa/ca-nist521.der" #define ECDSA_CA_CERT_DER "ecdsa/inter-nist521.der" #define ECDSA_EE_CERT_DER "ecdsa/end256-sha256.der" #define ECDSA_PRIV_KEY_DER "ecdsa/end256-sha256.key.der" typedef enum { SHALLOW_COPY = 0, DEEP_COPY, } COPY_WAY; typedef enum { ECDSA_CERT, ED25519_CERT, RSA_CERT, RSA_CERT_TWO, RSA_CERT_THREE, } EE_CERT_TYPE; typedef enum { FROM_CONFIG, FROM_CTX, FROM_BUFFER_TO_CONFIG, FROM_BUFFER_TO_CTX } LOAD_CERT_WAY; typedef LOAD_CERT_WAY LOAD_KEY_WAY; int GetCertPathFrom(int eeCertType, char **rootCA, char **ca, char **ee, char **prvKey) { switch (eeCertType) { case RSA_CERT: *rootCA = RSA_ROOT_CERT_DER; *ca = RSA_CA_CERT_DER; *ee = RSA_EE_CERT_DER; *prvKey = RSA_PRIV_KEY_DER; return SUCCESS; case RSA_CERT_TWO: *rootCA = RSA_ROOT_CERT2_DER; *ca = RSA_CA_CERT2_DER; *ee = RSA_EE_CERT2_DER; *prvKey = RSA_PRIV_KEY2_DER; return SUCCESS; case RSA_CERT_THREE: *rootCA = RSA_ROOT_CERT_DER; *ca = RSA_CA_CERT_DER; *ee = RSA_EE_CERT_DER; *prvKey = RSA_PRIV_KEY_DER; return SUCCESS; case ECDSA_CERT: *rootCA = ECDSA_ROOT_CERT_DER; *ca = ECDSA_CA_CERT_DER; *ee = ECDSA_EE_CERT_DER; *prvKey = ECDSA_PRIV_KEY_DER; return SUCCESS; default: return ERROR; } } int NormalizePath(char* normalizedPath, const char* path) { int ret; ret = sprintf_s(normalizedPath, CERT_PATH_LEN, "%s%s", DEFAULT_CERT_PATH, path); if (ret <= 0) { LOG_ERROR("sprintf_s Error"); return ERROR; } return SUCCESS; } int Dtls_DataTransfer(HITLS_Ctx *clientCtx, HLT_Process *remoteProcess, HLT_Tls_Res *serverRes) { uint8_t *writeBuf = (uint8_t *)"hello world"; uint32_t writeLen = strlen((char *)writeBuf); uint8_t readBuf[READ_DATA_18432] = { 0 }; uint32_t readLen = 0; ASSERT_EQ(HLT_TlsWrite(clientCtx, writeBuf, writeLen), SUCCESS); ASSERT_EQ(HLT_ProcessTlsRead(remoteProcess, serverRes, readBuf, READ_DATA_18432, &readLen), 0); ASSERT_COMPARE("COMPARE DATA", writeBuf, writeLen, readBuf, readLen); return SUCCESS; EXIT: return ERROR; } HITLS_Ctx *Dtls_New_Ctx(HLT_Process *localProcess, HITLS_Config* clientConfig) { HITLS_Ctx *clientCtx = HLT_TlsNewSsl(clientConfig); ASSERT_TRUE(clientCtx != NULL); HLT_Ssl_Config clientCtxConfig; clientCtxConfig.sockFd = localProcess->connFd; clientCtxConfig.connType = SCTP; ASSERT_TRUE_AND_LOG("HLT_TlsSetSsl", HLT_TlsSetSsl(clientCtx, &clientCtxConfig) == 0); return clientCtx; EXIT: return NULL; } void TestSetCertPath(HLT_Ctx_Config *ctxConfig, char *SignatureType) { if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA1", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA1")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA256", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA256")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA256_EE_PATH3, RSA_SHA256_PRIV_PATH3, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA384")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA384_EE_PATH, RSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PKCS1_SHA512", strlen("CERT_SIG_SCHEME_RSA_PKCS1_SHA512")) == 0 || strncmp(SignatureType, "CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512", strlen("CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512")) == 0) { HLT_SetCertPath( ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA512_EE_PATH, RSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256", strlen("CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA256_EE_PATH, ECDSA_SHA256_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384", strlen("CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA384_EE_PATH, ECDSA_SHA384_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512", strlen("CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA512_EE_PATH, ECDSA_SHA512_PRIV_PATH, "NULL", "NULL"); } else if (strncmp(SignatureType, "CERT_SIG_SCHEME_ECDSA_SHA1", strlen("CERT_SIG_SCHEME_ECDSA_SHA1")) == 0) { HLT_SetCertPath(ctxConfig, ECDSA_SHA1_CA_PATH, ECDSA_SHA1_CHAIN_PATH, ECDSA_SHA1_EE_PATH, ECDSA_SHA1_PRIV_PATH, "NULL", "NULL"); } } HITLS_CERT_X509 *HiTLS_X509_LoadCertFile(HITLS_Config *tlsCfg, const char *file); /* @ * @test SDV_TLS_LoadAndDelCert_FUNC_TC001 * @title Loading and Deleting Certificates * @precon nan * @brief 1. Initialize the client and server. Expected result 1 2. Load the certificate to the certificate chain. Expected result 2 3. Load the first certificate and private key to the certificate chain. Expected result 2 4. Load the second certificate to the certificate chain. Expected result 2 5. Run the config command to remove all certificates. Expected result 3 6. Load the third certificate to the certificate chain. Expected result 2 7. Remove all certificates in CTX mode. Expected result 3 8. Load the third certificate to the certificate chain. Expected result 2 9. Initiate link establishment. Expected result 4 is obtained * @expect 1. Initialization succeeded. 2. Loading succeeded. 3. Removing succeeded. 4. Link setup succeeded @ */ /* BEGIN_CASE */ void SDV_TLS_CERT_LoadAndDelCert_FUNC_TC001(int delWay) { if (!IsEnableSctpAuth()) { return; } HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HITLS_Config* serverConfig = NULL; // Stores the path where the certificate is loaded for the first time. char *rootCAFilePath1 = NULL; char *caFilePath1 = NULL; char *eeFilePath1 = NULL; char *eeKeyPath1 = NULL; // Stores the path where the certificate is loaded for the second time. char *rootCAFilePath2 = NULL; char *caFilePath2 = NULL; char *eeFilePath2 = NULL; char *eeKeyPath2 = NULL; HITLS_CERT_X509 *eeCert3 = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HILT_TransportType connType = SCTP; remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, false); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); TestSetCertPath(clientCtxConfig, "CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256"); rootCAFilePath1 = DEFAULT_CERT_PATH""RSA_ROOT_CERT_DER; caFilePath1 = DEFAULT_CERT_PATH""RSA_CA_CERT_DER; eeFilePath1 = DEFAULT_CERT_PATH""RSA_EE_CERT_DER; eeKeyPath1 = DEFAULT_CERT_PATH""RSA_PRIV_KEY_DER; rootCAFilePath2 = DEFAULT_CERT_PATH""ECDSA_ROOT_CERT_DER; caFilePath2 = DEFAULT_CERT_PATH""ECDSA_CA_CERT_DER; eeFilePath2 = DEFAULT_CERT_PATH""ECDSA_EE_CERT_DER; eeKeyPath2 = DEFAULT_CERT_PATH""ECDSA_PRIV_KEY_DER; ASSERT_EQ(HLT_TlsRegCallback(HITLS_CALLBACK_DEFAULT), SUCCESS); serverConfig = HLT_TlsNewCtx(DTLS1_2); ASSERT_TRUE(serverConfig != NULL); uint16_t group = HITLS_EC_GROUP_SECP256R1; ASSERT_EQ(HITLS_CFG_SetGroups(serverConfig, &group, 1), SUCCESS); // Load the certificate to the Chain Store. HITLS_CERT_Store *chainStore = HITLS_X509_Adapt_StoreNew(); ASSERT_TRUE(chainStore != NULL); ASSERT_EQ(HITLS_CFG_SetVerifyStore(serverConfig, chainStore, SHALLOW_COPY), SUCCESS); HITLS_CERT_X509 *rootCACert2 = HiTLS_X509_LoadCertFile(serverConfig, rootCAFilePath2); ASSERT_TRUE(rootCACert2 != NULL); ASSERT_EQ(HITLS_CFG_AddCertToStore(serverConfig, rootCACert2, TLS_CERT_STORE_TYPE_VERIFY, false), HITLS_SUCCESS); HITLS_CERT_X509 *caCert2 = HiTLS_X509_LoadCertFile(serverConfig, caFilePath2); ASSERT_TRUE(caCert2 != NULL); ASSERT_EQ(HITLS_CFG_AddCertToStore(serverConfig, caCert2, TLS_CERT_STORE_TYPE_VERIFY, false), HITLS_SUCCESS); // Loading the device certificate and corresponding private key for the first time HITLS_CERT_X509 *eeCert1 = HiTLS_X509_LoadCertFile(serverConfig, eeFilePath2); ASSERT_TRUE(eeCert1 != NULL); ASSERT_EQ(HITLS_CFG_SetCertificate(serverConfig, eeCert1, SHALLOW_COPY), SUCCESS); HITLS_CERT_Key *prvKey1 = HITLS_CFG_ParseKey(serverConfig, (const uint8_t *)eeKeyPath2, strlen(eeKeyPath1), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); ASSERT_TRUE(prvKey1 != NULL); ASSERT_EQ(HITLS_CFG_SetPrivateKey(serverConfig, prvKey1, SHALLOW_COPY), SUCCESS); // The private key is not loaded when the certificate is loaded for the second time. HITLS_CERT_X509 *eeCert2 = HiTLS_X509_LoadCertFile(serverConfig, eeFilePath2); ASSERT_TRUE(eeCert2 != NULL); ASSERT_EQ(HITLS_CFG_SetCertificate(serverConfig, eeCert2, SHALLOW_COPY), SUCCESS); ASSERT_TRUE(HITLS_CFG_GetCertificate(serverConfig) == eeCert2); if (delWay == FROM_CONFIG) { ASSERT_EQ(HITLS_CFG_RemoveCertAndKey(serverConfig), SUCCESS); // Reload the certificate without loading the private key. eeCert3 = HiTLS_X509_LoadCertFile(serverConfig, eeFilePath2); ASSERT_TRUE(eeCert3 != NULL); ASSERT_EQ(HITLS_CFG_SetCertificate(serverConfig, eeCert3, SHALLOW_COPY), SUCCESS); #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_Key *prvKey2 = HITLS_X509_Adapt_ProviderKeyParse(serverConfig, (const uint8_t *)eeKeyPath2, strlen(eeKeyPath2), TLS_PARSE_TYPE_FILE, "ASN1", NULL); #else HITLS_CERT_Key *prvKey2 = HITLS_X509_Adapt_KeyParse(serverConfig, (const uint8_t *)eeKeyPath2, strlen(eeKeyPath2), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); #endif ASSERT_TRUE(prvKey2 != NULL); ASSERT_EQ(HITLS_CFG_SetPrivateKey(serverConfig, prvKey2, SHALLOW_COPY), SUCCESS); ASSERT_TRUE(HITLS_CFG_GetPrivateKey(serverConfig) == prvKey2); } HITLS_Ctx *serverCtx = Dtls_New_Ctx(localProcess, serverConfig); ASSERT_TRUE(serverCtx != NULL); if (delWay == FROM_CTX) { // After the certificate is loaded from Config, the certificate is copied to CTX. ASSERT_TRUE(HITLS_GetCertificate(serverCtx) != eeCert2); ASSERT_EQ(HITLS_RemoveCertAndKey(serverCtx), SUCCESS); // Reload the certificate without loading the private key. eeCert3 = HiTLS_X509_LoadCertFile(serverConfig, eeFilePath2); ASSERT_TRUE(eeCert3 != NULL); ASSERT_EQ(HITLS_SetCertificate(serverCtx, eeCert3, SHALLOW_COPY), SUCCESS); #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_Key *prvKey2 = HITLS_X509_Adapt_ProviderKeyParse(serverConfig, (const uint8_t *)eeKeyPath2, strlen(eeKeyPath2), TLS_PARSE_TYPE_FILE, "ASN1", NULL); #else HITLS_CERT_Key *prvKey2 = HITLS_X509_Adapt_KeyParse(serverConfig, (const uint8_t *)eeKeyPath2, strlen(eeKeyPath2), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_ASN1); #endif ASSERT_TRUE(prvKey2 != NULL); ASSERT_EQ(HITLS_SetPrivateKey(serverCtx, prvKey2, SHALLOW_COPY), SUCCESS); ASSERT_TRUE(HITLS_GetCertificate(serverCtx) == eeCert3); ASSERT_TRUE(HITLS_GetPrivateKey(serverCtx) == prvKey2); } unsigned long int tlsAcceptId = HLT_TlsAccept(serverCtx); clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_GetTlsAcceptResultFromId(tlsAcceptId), 0); ASSERT_EQ(Dtls_DataTransfer(serverCtx, remoteProcess, clientRes), SUCCESS); EXIT: HLT_FreeAllProcess(); return; } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_sdv_hlt_cert_interface.c
C
unknown
15,849
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <unistd.h> #include <semaphore.h> #include "securec.h" #include "hlt.h" #include "logger.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "hitls.h" #include "process.h" #include "hitls_error.h" #include "hitls_type.h" #include "hitls_func.h" #include "hitls.h" #include "conn_init.h" #include "frame_tls.h" #include "frame_msg.h" #include "frame_io.h" #include "frame_link.h" #include "hs_common.h" #include "change_cipher_spec.h" #include "stub_replace.h" #define READ_BUF_SIZE 18432 #define Port 7788 #define ROOT_DER "%s/ca.der:%s/inter.der" #define INTCA_DER "%s/inter.der" #define SERVER_DER "%s/server.der" #define SERVER_KEY_DER "%s/server.key.der" #define CLIENT_DER "%s/client.der" #define CLIENT_KEY_DER "%s/client.key.der" #define BUF_SZIE 18432 /* END_HEADER */ static uint32_t g_uiPort = 18889; static void SetCertPath_2(HLT_Ctx_Config *ctxConfig, char *cipherSuite) { if (strstr(cipherSuite, "RSA") != NULL) { HLT_SetCertPath(ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, NULL, NULL); } else if (strstr(cipherSuite, "ECDSA") != NULL) { HLT_SetCertPath(ctxConfig, ECDSA_SHA_CA_PATH, ECDSA_SHA_CHAIN_PATH, ECDSA_SHA1_EE_PATH, ECDSA_SHA1_PRIV_PATH, NULL, NULL); } else { HLT_SetCertPath(ctxConfig, RSA_SHA_CA_PATH, RSA_SHA_CHAIN_PATH, RSA_SHA1_EE_PATH, RSA_SHA1_PRIV_PATH, NULL, NULL); } } /** * @test SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC001 * @title To test the setting of the HITLS_SetCipherServerPreference interface of the dtls. * @precon By default, the algorithm preferred by the client is preferred. * @brief * 1. Initialize the hitls. * 2. Create an SSL ctx object. * 3. Create an SSL object. * 4. Connect * 5. Check for connection errors. * 6. Check whether the negotiated cipher suite is the client preference. * 7. Check whether the negotiated group is the client preference. * 8. Check that the negotiated signature algorithm is the client preference. * @expect * 1. successful * 2. successful * 3. successful * 4. successful * 5. successful * 6. successful * 7. successful * 8. successful */ /* BEGIN_CASE */ void SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC001(char *serverCipherSuite, char *clientCipherSuite, int expectResult) { if (!IsEnableSctpAuth()) { return; } HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HILT_TransportType connType = SCTP; remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath_2(serverCtxConfig, serverCipherSuite); HLT_SetGroups(serverCtxConfig, "HITLS_EC_GROUP_SECP256R1:HITLS_EC_GROUP_SECP384R1"); HLT_SetCipherSuites(serverCtxConfig, serverCipherSuite); HLT_SetSignature(serverCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384:CERT_SIG_SCHEME_RSA_PKCS1_SHA512"); serverRes = HLT_ProcessTlsAccept(localProcess, DTLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath_2(clientCtxConfig, clientCipherSuite); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP384R1:HITLS_EC_GROUP_SECP256R1"); HLT_SetCipherSuites(clientCtxConfig, clientCipherSuite); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA512:CERT_SIG_SCHEME_RSA_PKCS1_SHA384"); clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[BUF_SZIE] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, sizeof(readBuf), &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); HITLS_Ctx *testCtx = (HITLS_Ctx *)serverRes->ssl; ASSERT_TRUE(testCtx->negotiatedInfo.cipherSuiteInfo.cipherSuite == expectResult); ASSERT_TRUE(testCtx->negotiatedInfo.negotiatedGroup == HITLS_EC_GROUP_SECP384R1); ASSERT_TRUE(testCtx->negotiatedInfo.signScheme == CERT_SIG_SCHEME_RSA_PKCS1_SHA512); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** * @test SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC002 * @title To test the setting of the HITLS_SetCipherServerPreference interface of the dtls. * @precon Set the algorithm for preferentially selecting the server-side preference. * @brief * 1. Initialize the hitls. * 2. Create an SSL ctx object. * 3. Create an SSL object. * 4. Connect * 5. Check for connection errors. * 6. Check whether the negotiated algorithm is the server preference. * @expect * 1. successful * 2. successful * 3. successful * 4. successful * 5. successful * 6. successful */ /* BEGIN_CASE */ void SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC002(char *serverCipherSuite, char *clientCipherSuite, int expectResult) { if (!IsEnableSctpAuth()) { return; } HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HILT_TransportType connType = SCTP; remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath_2(serverCtxConfig, serverCipherSuite); HLT_SetGroups(serverCtxConfig, "NULL"); HLT_SetCipherSuites(serverCtxConfig, serverCipherSuite); HLT_SetSignature(serverCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384:CERT_SIG_SCHEME_RSA_PKCS1_SHA512"); serverRes = HLT_ProcessTlsAccept(localProcess, DTLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); int32_t ret = HITLS_SetCipherServerPreference(serverRes->ssl, true); ASSERT_TRUE(ret == HITLS_SUCCESS); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath_2(clientCtxConfig, clientCipherSuite); HLT_SetGroups(clientCtxConfig, "NULL"); HLT_SetCipherSuites(clientCtxConfig, clientCipherSuite); HLT_SetSignature(clientCtxConfig, "NULL"); clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[BUF_SZIE] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, sizeof(readBuf), &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); HITLS_Ctx *testCtx = (HITLS_Ctx *)serverRes->ssl; ASSERT_TRUE(testCtx->negotiatedInfo.cipherSuiteInfo.cipherSuite == expectResult); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** * @test SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC003 * @title To test the setting of the HITLS_SetCipherServerPreference interface of the dtls. * @precon Set the signature algorithm preferred by the server. * @brief * 1. Initialize the hitls. * 2. Create an SSL ctx object. * 3. Create an SSL object. * 4. Connect * 5. Check for connection errors. * 6. Check whether the negotiated signature algorithm is the server preference. * @expect * 1. successful * 2. successful * 3. successful * 4. successful * 5. successful * 6. successful */ /* BEGIN_CASE */ void SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC003(char *serverCipherSuite, char *clientCipherSuite) { if (!IsEnableSctpAuth()) { return; } HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HILT_TransportType connType = SCTP; remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath_2(serverCtxConfig, serverCipherSuite); HLT_SetCipherSuites(serverCtxConfig, serverCipherSuite); HLT_SetGroups(serverCtxConfig, "NULL"); HLT_SetSignature(serverCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA384:CERT_SIG_SCHEME_RSA_PKCS1_SHA512"); serverRes = HLT_ProcessTlsAccept(localProcess, DTLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); int32_t ret = HITLS_SetCipherServerPreference(serverRes->ssl, true); ASSERT_TRUE(ret == HITLS_SUCCESS); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath_2(clientCtxConfig, clientCipherSuite); HLT_SetCipherSuites(clientCtxConfig, clientCipherSuite); HLT_SetGroups(clientCtxConfig, "NULL"); HLT_SetSignature(clientCtxConfig, "CERT_SIG_SCHEME_RSA_PKCS1_SHA512:CERT_SIG_SCHEME_RSA_PKCS1_SHA384"); clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[BUF_SZIE] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, sizeof(readBuf), &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); HITLS_Ctx *testCtx = (HITLS_Ctx *)serverRes->ssl; ASSERT_TRUE(testCtx->negotiatedInfo.signScheme == CERT_SIG_SCHEME_RSA_PKCS1_SHA384); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ /** * @test SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC004 * @title To test the setting of the HITLS_SetCipherServerPreference interface of the dtls. * @precon Set the preference group of the server. * @brief * 1. Initialize the hitls. * 2. Create an SSL ctx object. * 3. Create an SSL object. * 4. Connect * 5. Check for connection errors. * 6. Check whether the negotiated group is the server preference. * @expect * 1. successful * 2. successful * 3. successful * 4. successful * 5. successful * 6. successful */ /* BEGIN_CASE */ void SDV_HITLS_CM_HITLS_GetNegotiateGroup_FUNC_TC004(char *serverCipherSuite, char *clientCipherSuite) { if (!IsEnableSctpAuth()) { return; } HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HILT_TransportType connType = SCTP; remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, g_uiPort, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); SetCertPath_2(serverCtxConfig, serverCipherSuite); HLT_SetCipherSuites(serverCtxConfig, serverCipherSuite); HLT_SetGroups(serverCtxConfig, "HITLS_EC_GROUP_SECP256R1:HITLS_EC_GROUP_SECP384R1"); HLT_SetSignature(serverCtxConfig, "NULL"); serverRes = HLT_ProcessTlsAccept(localProcess, DTLS1_2, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); int32_t ret = HITLS_SetCipherServerPreference(serverRes->ssl, true); ASSERT_TRUE(ret == HITLS_SUCCESS); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); SetCertPath_2(clientCtxConfig, clientCipherSuite); HLT_SetCipherSuites(clientCtxConfig, clientCipherSuite); HLT_SetGroups(clientCtxConfig, "HITLS_EC_GROUP_SECP384R1:HITLS_EC_GROUP_SECP256R1"); HLT_SetSignature(clientCtxConfig, "NULL"); clientRes = HLT_ProcessTlsConnect(remoteProcess, DTLS1_2, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[BUF_SZIE] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, sizeof(readBuf), &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); HITLS_Ctx *testCtx = (HITLS_Ctx *)serverRes->ssl; ASSERT_TRUE(testCtx->negotiatedInfo.negotiatedGroup == HITLS_EC_GROUP_SECP256R1); EXIT: HLT_FreeAllProcess(); } /* END_CASE */ int32_t REC_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len); int32_t STUB_REC_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len) { (void)ctx; *len = 100; return HITLS_SUCCESS; } /* @ * @test SDV_TLS_CM_FRAGMENTATION_FUNC_TC001 * @title DTLS Message Fragmentation * @precon nan * @brief * 1. Initialize the client and server processes. * 2. The interface for obtaining the maximum message length is stubbed and the maximum message length is changed to 100. * 3. Creat and connect linck. * @expect * 1. The initialization is successful. * 2. The stub is successful. * 3. The link is set up successfully. @ */ /* BEGIN_CASE */ void SDV_TLS_CM_FRAGMENTATION_FUNC_TC001(void) { if (!IsEnableSctpAuth()) { return; } HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; HLT_Ctx_Config *serverConfig = NULL; HLT_Ctx_Config *clientConfig = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); HILT_TransportType connType = SCTP; remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, Port, false); ASSERT_TRUE(remoteProcess != NULL); serverConfig = HLT_NewCtxConfig(NULL, "SERVER"); clientConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(serverConfig != NULL); ASSERT_TRUE(clientConfig != NULL); serverRes = HLT_ProcessTlsAccept(remoteProcess, DTLS1_2, serverConfig, NULL); ASSERT_TRUE(serverRes != NULL); STUB_Init(); FuncStubInfo stubInfo = {0}; STUB_Replace(&stubInfo, REC_GetMaxWriteSize, STUB_REC_GetMaxWriteSize); clientRes = HLT_ProcessTlsInit(localProcess, DTLS1_2, clientConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) == 0); EXIT: STUB_Reset(&stubInfo); HLT_FreeAllProcess(); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_sdv_hlt_cm_interface.c
C
unknown
15,727
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* BEGIN_HEADER */ #include <stdlib.h> #include <semaphore.h> #include <unistd.h> #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/select.h> #include <sys/time.h> #include <linux/ioctl.h> #include "securec.h" #include "bsl_sal.h" #include "alert.h" #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_crypt_reg.h" #include "hitls_config.h" #include "tls_config.h" #include "hitls.h" #include "hitls_func.h" #include "pack_frame_msg.h" #include "hlt.h" #include "logger.h" #include "hitls_cert_type.h" #include "crypt_util_rand.h" #include "common_func.h" #include "frame_tls.h" #include "conn_init.h" #include "tls.h" #include "simulate_io.h" #include "frame_io.h" #include "frame_link.h" #include "stub_replace.h" #include "session_type.h" #include "cert_callback.h" #include "bsl_sal.h" #include "sal_net.h" #include "parse_msg.h" #include "hs_msg.h" #include "hitls_crypt_init.h" #include "uio_abstraction.h" #include "process.h" #include "rec_wrapper.h" #include "hs_ctx.h" #include "hitls_type.h" /* END_HEADER */ #define Port 7788 #define READ_BUF_SIZE 18432 #define ROOT_DER "%s/ca.der:%s/inter.der" #define INTCA_DER "%s/inter.der" #define SERVER_DER "%s/server.der" #define SERVER_KEY_DER "%s/server.key.der" #define CLIENT_DER "%s/client.der" #define CLIENT_KEY_DER "%s/client.key.der" #define RENEGOTIATE_FAIL 1 #define MAX_CERT_LIST 4294967295 #define MIN_CERT_LIST 0 static uint32_t g_useFlight = 0; /* Range required in the test case */ static uint32_t g_flag; /* Used to record the number of handshake messages in the current flight. */ static uint32_t g_flight = 0; /* is used to record the number of the current flight */ static HLT_FrameHandle g_frameHandle; static HITLS_Config *GetHitlsConfigViaVersion(int ver) { switch (ver) { case TLS1_2: case HITLS_VERSION_TLS12: return HITLS_CFG_NewTLS12Config(); case TLS1_3: case HITLS_VERSION_TLS13: return HITLS_CFG_NewTLS13Config(); case DTLS1_2: case HITLS_VERSION_DTLS12: return HITLS_CFG_NewDTLS12Config(); default: return NULL; } } static void TEST_MsgHandle(void *msg, void *data) { (void)data; (void)msg; } /* Verify whether the parsed msg meets the requirements. Restrict the msg input parameter. */ static bool CheckHandleType(FRAME_Msg *msg) { if (msg->recType.data != REC_TYPE_HANDSHAKE) { if (msg->recType.data == (uint64_t)g_frameHandle.expectReType) { return true; } } else { if (msg->recType.data == (uint64_t)g_frameHandle.expectReType && msg->body.hsMsg.type.data == (uint64_t)g_frameHandle.expectHsType) { return true; } } return false; } /* Obtain the frameType. The input parameters frameHandle and frameType must not be empty. */ static int32_t GetFrameType(HLT_FrameHandle *frameHandle, FRAME_Type *frameType) { if (frameHandle->ctx == NULL) { return HITLS_NULL_INPUT; } TLS_Ctx *tmpCtx = (TLS_Ctx *)frameHandle->ctx; frameType->versionType = tmpCtx->negotiatedInfo.version > 0 ? tmpCtx->negotiatedInfo.version : tmpCtx->config.tlsConfig.maxVersion; frameType->keyExType = tmpCtx->hsCtx->kxCtx->keyExchAlgo; frameType->recordType = frameHandle->expectReType; frameType->handshakeType = frameHandle->expectHsType; return HITLS_SUCCESS; } static int32_t STUB_Write(BSL_UIO *uio, const void *buf, uint32_t len, uint32_t *writeLen) { FRAME_Msg msg = {0}; uint32_t parseLen = 0; uint32_t offset = 0; uint32_t msgCnt = 0; FRAME_Type frameType = { 0 }; (void)GetFrameType(&g_frameHandle, &frameType); g_flight++; while (offset < len) { (void)FRAME_ParseMsgHeader(&frameType, &((uint8_t*)buf)[offset], len - offset, &msg, &parseLen); offset += parseLen + msg.length.data; if (g_flight == g_useFlight) { msgCnt++; } FRAME_CleanMsg(&frameType, &msg); } if (CheckHandleType(&msg) && g_flight == g_useFlight) { g_flag = msgCnt; } return BSL_UIO_TcpMethod()->uioWrite(uio, buf, len, writeLen); } static int SetCertPath(HLT_Ctx_Config *ctxConfig, const char *certStr, bool isServer) { char caCertPath[50]; char chainCertPath[30]; char eeCertPath[30]; char privKeyPath[30]; int32_t ret = sprintf_s(caCertPath, sizeof(caCertPath), ROOT_DER, certStr, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(chainCertPath, sizeof(chainCertPath), INTCA_DER, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(eeCertPath, sizeof(eeCertPath), isServer ? SERVER_DER : CLIENT_DER, certStr); ASSERT_TRUE(ret > 0); ret = sprintf_s(privKeyPath, sizeof(privKeyPath), isServer ? SERVER_KEY_DER : CLIENT_KEY_DER, certStr); ASSERT_TRUE(ret > 0); HLT_SetCaCertPath(ctxConfig, (char *)caCertPath); HLT_SetChainCertPath(ctxConfig, (char *)chainCertPath); HLT_SetEeCertPath(ctxConfig, (char *)eeCertPath); HLT_SetPrivKeyPath(ctxConfig, (char *)privKeyPath); return 0; EXIT: return -1; } /* @ * @test SDV_TLS_CFG_SET_GET_VERIFYNONESUPPORT_FUNC_TC001 * @title The server does not verify the client certificate. * @precon nan * @brief * 1. The server invokes the HITLS_CFG_SetVerifyNoneSupport and sets the parameter to false. Expected result 1 is * obtained. * 2. The server invokes the HITLS_CFG_SetVerifyNoneSupport interface to obtain the configuration result. (Expected * result 2) * 3. The server invokes the HITLS_SetVerifyNoneSupport interface and sets it to true. Expected result 3 is obtained. * 4. The server invokes the HITLS_GetVerifyNoneSupport interface to obtain the configuration result. (Expected result 4) * 4. Establish a connection. Expected result 4 is obtained. * @expect * 1. The setting is successful. * 2. The setting is successful. * 3. The setting is successful. * 4. The connection is successfully established. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_SET_GET_VERIFYNONESUPPORT_FUNC_TC001(int version, int connType) { HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; uint8_t c_flag = 0; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, connType, Port, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); ASSERT_EQ(SetCertPath(serverCtxConfig, "ecdsa_sha256", true), 0); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); serverRes = HLT_ProcessTlsAccept(localProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HITLS_SetVerifyNoneSupport(serverRes->ssl, true); HITLS_GetVerifyNoneSupport(serverRes->ssl, &c_flag); ASSERT_TRUE(c_flag == 1); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetCertPath(clientCtxConfig, "ecdsa_sha256/ca.der", "NULL", "NULL", "NULL", "NULL", "NULL"); HLT_SetCipherSuites(serverCtxConfig, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"); clientRes = HLT_ProcessTlsInit(remoteProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); ASSERT_EQ(HLT_RpcTlsConnect(remoteProcess, clientRes->sslId), HITLS_SUCCESS); ASSERT_TRUE(HLT_GetTlsAcceptResult(serverRes) == 0); ASSERT_TRUE(HLT_ProcessTlsWrite(localProcess, serverRes, (uint8_t *)"Hello World", strlen("Hello World")) == 0); uint8_t readBuf[READ_BUF_SIZE] = {0}; uint32_t readLen; ASSERT_TRUE(HLT_ProcessTlsRead(remoteProcess, clientRes, readBuf, sizeof(readBuf), &readLen) == 0); ASSERT_TRUE(readLen == strlen("Hello World")); ASSERT_TRUE(memcmp("Hello World", readBuf, readLen) == 0); EXIT: HLT_CleanFrameHandle(); HLT_FreeAllProcess(); } /* END_CASE */ /** @ * @test HITLS_TLS1_2_Config_SDV_23_0_5_047 * @title Enable dual-end verification. The server verifies the client certificate only once. * @precon nan * @brief * 1. The server invokes the HITLS_CFG_SetClientVerifySupport and sets the parameter to true. * 2. Set the value of HITLS_CFG_SetClientOnceVerifySupport to false when the server invokes the * HITLS_CFG_SetClientOnceVerifySupport. * 3. The server invokes the HITLS_CFG_SetClientOnceVerifySupport interface to obtain the configuration result. * 4. The server invokes the HITLS_SetClientOnceVerifySupport interface and sets it to true. * 5. The server invokes the HITLS_SetClientOnceVerifySupport interface to obtain the configuration result. * 6. Establish a connection. After the connection is established, perform renegotiation. Stop the status on the server to * TRY_SEND_CERTIFICATIONATE_REQUEST. The expected result is obtained. * @expect * 1. If the status fails to be stopped, the certificate will not be verified during the renegotiation. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_SET_GET_CLIENTVERIFYUPPORT_FUNC_TC001(int clientverify) { FRAME_Init(); HITLS_Config *config_c = NULL; HITLS_Config *config_s = NULL; FRAME_LinkObj *client = NULL; FRAME_LinkObj *server = NULL; config_c = HITLS_CFG_NewTLS12Config(); config_s = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(config_c != NULL); ASSERT_TRUE(config_s != NULL); uint8_t c_flag; if (clientverify) { HITLS_CFG_SetClientVerifySupport(config_s, true); } else { HITLS_CFG_SetClientVerifySupport(config_s, false); } HITLS_CFG_SetClientOnceVerifySupport(config_s, false); HITLS_CFG_GetClientOnceVerifySupport(config_s, &c_flag); ASSERT_TRUE(c_flag == 0); client = FRAME_CreateLink(config_c, BSL_UIO_TCP); ASSERT_TRUE(client != NULL); server = FRAME_CreateLink(config_s, BSL_UIO_TCP); ASSERT_TRUE(server != NULL); HITLS_SetClientOnceVerifySupport(server->ssl, true); HITLS_GetClientOnceVerifySupport(server->ssl, &c_flag); ASSERT_TRUE(c_flag == 1); HITLS_SetRenegotiationSupport(server->ssl, true); HITLS_SetRenegotiationSupport(client->ssl, true); HITLS_GetRenegotiationSupport(server->ssl, &c_flag); ASSERT_TRUE(c_flag == 1); ASSERT_EQ(FRAME_CreateConnection(client, server, true, HS_STATE_BUTT), HITLS_SUCCESS); uint8_t verifyDataNew[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataNewSize = 0; uint8_t verifyDataOld[MAX_DIGEST_SIZE] = {0}; uint32_t verifyDataOldSize = 0; ASSERT_TRUE(HITLS_GetFinishVerifyData(server->ssl, verifyDataOld, sizeof(verifyDataOld), &verifyDataOldSize) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(client->ssl) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_Renegotiate(server->ssl) == HITLS_SUCCESS); ASSERT_EQ(FRAME_CreateRenegotiationState(client, server, false, TRY_SEND_CERTIFICATE_REQUEST), HITLS_INTERNAL_EXCEPTION); ASSERT_TRUE(HITLS_GetFinishVerifyData(server->ssl, verifyDataNew, sizeof(verifyDataNew), &verifyDataNewSize) == HITLS_SUCCESS); ASSERT_TRUE(memcmp(verifyDataNew, verifyDataOld, verifyDataOldSize) != 0); EXIT: HITLS_CFG_FreeConfig(config_c); HITLS_CFG_FreeConfig(config_s); FRAME_FreeLink(client); FRAME_FreeLink(server); } /* END_CASE */ /** @ * @test SDV_TLS_CFG_ADD_CAINDICATION_FUNC_TC001 * @title: Add different CA flag indication types. * @precon nan * @brief * 1. Invoke the HITLS_CFG_AddCAIndication interface and set the transferred caType to HITLS_TRUSTED_CA_PRE_AGREED and * HITLS_TRUSTED_CA_PRE_AGREED respectively. HITLS_TRUSTED_CA_KEY_SHA1, HITLS_TRUSTED_CA_X509_NAME, * HITLS_TRUSTED_CA_CERT_SHA1, When the HITLS_TRUSTED_CA_UNKNOWN macro is used, expected result 1 is obtained. * 2. Check the return value of the interface. Expected result 2 is obtained. * @expect * 1. The invoking is successful. * 2. The interface returns HITLS_SUCCESS. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_ADD_CAINDICATION_FUNC_TC001(int tlsVersion) { FRAME_Init(); HITLS_Config *config = NULL; uint8_t data[] = {0}; uint32_t len = sizeof(data); config = GetHitlsConfigViaVersion(tlsVersion); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_PRE_AGREED, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_KEY_SHA1, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_X509_NAME, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_CERT_SHA1, data, len) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_AddCAIndication(config, HITLS_TRUSTED_CA_UNKNOWN, data, len) == HITLS_SUCCESS); EXIT: HITLS_CFG_FreeConfig(config); } /* END_CASE */ /** @ * @test SDV_TLS_CFG_GET_CIPHERBYID_FUNC_TC001 * @title Obtain the CipherId based on the known cipher suite. * @precon nan * @brief * 1. Invoke the HITLS_CFG_GetCipherByID and set the transferred id to the HITLS_AES_128_GCM_SHA256 macro to obtain the * HITLS_Cipher structure. (Expected result 1) * 2. Invoke the HITLS_CFG_GetCipherId interface and transfer the obtained structure. (Expected result 2) * @expect * 1. The interface returns the corresponding HITLS_Cipher structure. * 2. HITLS_CIPHER_AES_128_GCM is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_GET_CIPHERBYID_FUNC_TC001() { FRAME_Init(); HITLS_CipherAlgo cipherAlgo; const HITLS_Cipher* cipher = HITLS_CFG_GetCipherByID(HITLS_AES_128_GCM_SHA256); HITLS_CFG_GetCipherId(cipher, &cipherAlgo); ASSERT_EQ(cipherAlgo, HITLS_CIPHER_AES_128_GCM); EXIT: return; } /* END_CASE */ /** @ * @test SDV_TLS_CFG_GET_AUTHID_FUNC_TC001 * @title Self-registration cipher. Invoke the interface to obtain the AuthId. * @precon nan * @brief * 1. Register a HITLS_Cipher structure, set cipherid to HITLS_AUTH_NULL, and call HITLS_CFG_GetAuthId. Expected result 1 * is obtained. * @expect * 1. HITLS_AUTH_NULL is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_GET_AUTHID_FUNC_TC001() { FRAME_Init(); HITLS_AuthAlgo cipherSuite; HITLS_Cipher *cipher = (HITLS_Cipher *)malloc(sizeof(HITLS_Cipher)); cipher->authAlg = HITLS_AUTH_NULL; HITLS_CFG_GetAuthId(cipher, &cipherSuite); ASSERT_EQ(cipherSuite, HITLS_AUTH_NULL); EXIT: free(cipher); } /* END_CASE */ /** @ * @test SDV_TLS_CFG_GET_CIPHERSUITENAME_FUNC_TC001 * @title Query the name of the algorithm suite. * @precon nan * @brief * 1. Set cipher to HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 and invoke the HITLS_CFG_GetCipherSuiteName interface. * Expected result 1 is obtained. * @expect * 1. Return value of the char* conversion interface, which is the same as that of the * HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_GET_CIPHERSUITENAME_FUNC_TC001() { FRAME_Init(); const HITLS_Cipher* cipher = HITLS_CFG_GetCipherByID(HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256); const uint8_t* name = HITLS_CFG_GetCipherSuiteName(cipher); ASSERT_TRUE(strcmp((char *)name, "HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") == 0); EXIT: return; } /* END_CASE */ /** @ * @test SDV_TLS_CFG_GET_CIPHERVERSION_FUNC_TC001 * @title Query the cipher suite version and obtain the algorithm based on the ID. * @precon nan * @brief * 1. Set cipher to HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 () and invoke the HITLS_CFG_GetCipherVersion interface. * (Expected result 1) * 2. Set cipher to HITLS_AES_128_GCM_SHA256 () and invoke the HITLS_CFG_GetCipherVersion interface. (Expected result 2) * 3. Set cipher to HITLS_RSA_WITH_AES_128_CBC_SHA () and invoke the HITLS_CFG_GetCipherVersion interface. (Expected * result 3) * @expect * 1. Interface return value: HITLS_VERSION_TLS12 * 2. Interface return value: HITLS_VERSION_TLS13, HITLS_VERSION_TLS13 * 3. Interface return value: HITLS_VERSION_SSL30 @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_GET_CIPHERVERSION_FUNC_TC001() { FRAME_Init(); int32_t version; const HITLS_Cipher *cipher = HITLS_CFG_GetCipherByID(HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256); ASSERT_EQ(HITLS_CFG_GetCipherVersion(cipher, &version), HITLS_SUCCESS); ASSERT_EQ(HITLS_VERSION_TLS12, version); cipher = HITLS_CFG_GetCipherByID(HITLS_AES_128_GCM_SHA256); ASSERT_EQ(HITLS_CFG_GetCipherVersion(cipher, &version), HITLS_SUCCESS); ASSERT_EQ(HITLS_VERSION_TLS13, version); cipher = HITLS_CFG_GetCipherByID(HITLS_RSA_WITH_AES_128_CBC_SHA); ASSERT_EQ(HITLS_CFG_GetCipherVersion(cipher, &version), HITLS_SUCCESS); ASSERT_EQ(HITLS_VERSION_SSL30, version); EXIT: version = 1; } /* END_CASE */ /** @ * @test SDV_TLS_CFG_GET_CIPHERSUITE_FUNC_TC001 * @title Obtain the cipher suite based on the supported cipher suite ID. * @precon nan * @brief * 1. Invoke the HITLS_CFG_GetCipherByID and set the input ID to the HITLS_AES_128_GCM_SHA256 macro to obtain the * cipherinfo structure. Expected result 1 is obtained. * 2. Invoke the HITLS_CFG_GetCipherSuite interface and transfer the obtained structure. (Expected result 2) * @expect * 1. The interface returns the corresponding HITLS_Cipher structure. * 2. HITLS_AES_128_GCM_SHA256 is returned. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_GET_CIPHERSUITE_FUNC_TC001() { FRAME_Init(); uint16_t cipherSuite; const HITLS_Cipher* cipher = HITLS_CFG_GetCipherByID(HITLS_AES_128_GCM_SHA256); HITLS_CFG_GetCipherSuite(cipher, &cipherSuite); ASSERT_EQ(cipherSuite, HITLS_AES_128_GCM_SHA256); EXIT: return; } /* END_CASE */ /** @ * @test SDV_TLS_CFG_GET_FLIGHTTRANSMITSWITH_FUNC_TC001 * @titleThe client sends messages by flight. * @precon nan * @brief 1. The server invokes the HITLS_CFG_SetFlightTransmitSwitch interface and sets the parameter to false. Expected result 1 is obtained. 2. The server invokes the HITLS_CFG_GetFlightTransmitSwitch interface to obtain the configuration result. (Expected result 2) 3. The client invokes the HITLS_SetFlightTransmitSwitch interface to set the parameter to true. Expected result 3 is obtained. 4. The client invokes the HITLS_GetFlightTransmitSwitch interface to obtain the configuration result. Expected result 4 is obtained. 5. Establish a link and count the number of messages sent by the client in the second flight. Expected result 5 is obtained. * @expect 1. The setting is successful. 2. The obtained result is false. 3. The setting is successful. 4. The obtained result is true. 5. The connection is set up successfully, and the number of the second flight messages sent by the client is 3. @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_GET_FLIGHTTRANSMITSWITH_FUNC_TC001(int version) { FRAME_Init(); HITLS_Config *Config = NULL; HITLS_Ctx *ctx = NULL; uint8_t support; Config = GetHitlsConfigViaVersion(version); ASSERT_TRUE(Config != NULL); ctx = HITLS_New(Config); ASSERT_TRUE(ctx != NULL); HITLS_CFG_SetFlightTransmitSwitch(Config, false); HITLS_CFG_GetFlightTransmitSwitch(Config, &support); ASSERT_TRUE(support == false); HITLS_SetFlightTransmitSwitch(ctx, true); HITLS_GetFlightTransmitSwitch(ctx, &support); ASSERT_TRUE(support == true); HLT_Tls_Res *serverRes = NULL; HLT_Tls_Res *clientRes = NULL; HLT_Process *localProcess = NULL; HLT_Process *remoteProcess = NULL; localProcess = HLT_InitLocalProcess(HITLS); ASSERT_TRUE(localProcess != NULL); remoteProcess = HLT_LinkRemoteProcess(HITLS, TCP, Port, true); ASSERT_TRUE(remoteProcess != NULL); HLT_Ctx_Config *serverCtxConfig = HLT_NewCtxConfig(NULL, "SERVER"); ASSERT_TRUE(serverCtxConfig != NULL); HLT_SetFlightTransmitSwitch(serverCtxConfig, false); serverRes = HLT_ProcessTlsAccept(remoteProcess, version, serverCtxConfig, NULL); ASSERT_TRUE(serverRes != NULL); HLT_Ctx_Config *clientCtxConfig = HLT_NewCtxConfig(NULL, "CLIENT"); ASSERT_TRUE(clientCtxConfig != NULL); HLT_SetFlightTransmitSwitch(clientCtxConfig, true); clientRes = HLT_ProcessTlsInit(localProcess, version, clientCtxConfig, NULL); ASSERT_TRUE(clientRes != NULL); HLT_FrameHandle frameHandle = { .ctx = clientRes->ssl, .frameCallBack = TEST_MsgHandle, .userData = NULL, .expectHsType = CLIENT_KEY_EXCHANGE, .expectReType = REC_TYPE_HANDSHAKE, .ioState = EXP_NONE, .pointType = POINT_SEND, .method.uioWrite = STUB_Write, }; ASSERT_TRUE(HLT_SetFrameHandle(&frameHandle) == HITLS_SUCCESS); g_useFlight = 2; ASSERT_TRUE(HLT_TlsConnect(clientRes->ssl) == HITLS_SUCCESS); if (version == TLS1_2) { ASSERT_EQ(g_flag, 3); } else { ASSERT_EQ(g_flag, 2); } HLT_CleanFrameHandle(); EXIT: g_flag = 0; g_flight = 0; HLT_CleanFrameHandle(); HLT_FreeAllProcess(); HITLS_CFG_FreeConfig(Config); HITLS_Free(ctx); return; } /* END_CASE */ /** @ * @test SDV_TLS_CFG_GET_MAXCERTLIST_API_TC001 * @title HTLS_CFG_SetMaxCertList, HITLS_CFG_GetMaxCertList, HITLS_SetMaxCertList, and HITLS_GetMaxCertList APIs * @precon nan * @brief * 1. Apply for and initialize config and ctx. * 2. Set the certificate chain length config to null and invoke the HITLS_CFG_SetMaxCertList interface. * 3. Invoke the HITLS_CFG_GetMaxCertList interface and check the output parameter value. * 4. Set the maximum length of the certificate chain by calling the HITLS_CFG_SetMaxCertList interface. * 5. Invoke the HITLS_CFG_GetMaxCertList interface and check the output parameter value. * 6. Set the minimum certificate chain length by calling the HITLS_CFG_SetMaxCertList interface. * 7. Invoke the HITLS_CFG_GetMaxCertList interface and check the output parameter value. * 8. Use the HITLS_SetMaxCertList and HITLS_GetMaxCertList interfaces to repeat the preceding test. * @expect * 1. Initialization succeeds. * 2. HITLS_NULL_INPUT is returned. * 3. HITLS_NULL_INPUT is returned. * 4. The interface returns HITLS_SUCCESS. * 5. The value of MaxCertList returned by the interface is 2 ^ 32 - 1. * 6. The interface returns the HITLS_SUCCESS. * 7. The value of MaxCertList returned by the interface is 0. * 8. Same as above @ */ /* BEGIN_CASE */ void SDV_TLS_CFG_GET_MAXCERTLIST_API_TC001() { FRAME_Init(); HITLS_Config *tlsConfig; HITLS_Ctx *ctx = NULL; tlsConfig = HITLS_CFG_NewTLS12Config(); ASSERT_TRUE(tlsConfig != NULL); ctx = HITLS_New(tlsConfig); ASSERT_TRUE(ctx != NULL); uint32_t maxSize; ASSERT_TRUE(HITLS_CFG_SetMaxCertList(NULL, MAX_CERT_LIST) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_GetMaxCertList(NULL, &maxSize) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_CFG_SetMaxCertList(tlsConfig, MAX_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxCertList(tlsConfig, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MAX_CERT_LIST); ASSERT_TRUE(HITLS_CFG_SetMaxCertList(tlsConfig, MIN_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_CFG_GetMaxCertList(tlsConfig, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MIN_CERT_LIST); ASSERT_TRUE(HITLS_SetMaxCertList(NULL, MAX_CERT_LIST) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_GetMaxCertList(NULL, &maxSize) == HITLS_NULL_INPUT); ASSERT_TRUE(HITLS_SetMaxCertList(ctx, MAX_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetMaxCertList(ctx, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MAX_CERT_LIST); ASSERT_TRUE(HITLS_SetMaxCertList(ctx, MIN_CERT_LIST) == HITLS_SUCCESS); ASSERT_TRUE(HITLS_GetMaxCertList(ctx, &maxSize) == HITLS_SUCCESS); ASSERT_TRUE(maxSize == MIN_CERT_LIST); EXIT: HITLS_CFG_FreeConfig(tlsConfig); HITLS_Free(ctx); } /* END_CASE */
2302_82127028/openHiTLS-examples_5062_4009
testcode/sdv/testcase/tls/interface_tlcp/test_suite_sdv_hlt_config_interface.c
C
unknown
24,545
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 ALTER_H #define ALTER_H #include <stdbool.h> #include <stdint.h> #include "hitls_build.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif typedef enum { ALERT_FLAG_NO = 0, /* no alert message */ ALERT_FLAG_RECV, /* received the alert message */ ALERT_FLAG_SEND, /* the alert message needs to be sent */ } ALERT_FLAG; /** obtain the messages about receiving and sending by Alert */ typedef struct { uint8_t flag; /* send and receive flags, see ALERT_FLAG */ uint8_t level; /* Alert level. For details, see ALERT_Level. */ uint8_t description; /* Alert description. For details, see ALERT_Description. */ uint8_t reverse; /* reserve, 4-byte aligned */ } ALERT_Info; /** * @ingroup alert * @brief Alert initialization function * * @param ctx [IN] tls Context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_INTERNAL_EXCEPTION An unexpected internal error occurs. * @retval HITLS_MEMALLOC_FAIL Failed to apply for memory. */ int32_t ALERT_Init(TLS_Ctx *ctx); /** * @ingroup alert * @brief Alert deinitialization function * * @param ctx [IN] tls Context * */ void ALERT_Deinit(TLS_Ctx *ctx); /** * @ingroup alert * @brief Check whether there are received or sent alert messages to be processed. * * @attention ctx cannot be empty. * @param ctx [IN] tls Context * * @retval true: The processing is required. * @retval false: No processing is required. */ bool ALERT_GetFlag(const TLS_Ctx *ctx); /** * @ingroup alert * @brief Obtain the alert information. * * @attention ctx and info cannot be empty. Ensure that the value is used when Alert_GetFlag is true. * @param ctx [IN] tls Context * @param info [IN] Alert information record */ void ALERT_GetInfo(const TLS_Ctx *ctx, ALERT_Info *info); /** * @brief Clear the alert information. * * @attention ctx cannot be empty. * @param ctx [IN] tls Context */ void ALERT_CleanInfo(const TLS_Ctx *ctx); /** * @brief Send an alert message and cache it in the alert module. * * @attention ctx cannot be empty. * @param ctx [IN] tls Context * @param level [IN] Alert level * @param description [IN] alert Description * */ void ALERT_Send(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description); /** * @brief Send the alert message cached by the alert module to the network layer. * * @attention ctx cannot be empty. Alert_Send must be invoked before flushing. * @param ctx [IN] tls Context * * @retval HITLS_SUCCESS succeeded. * @retval See REC_Write */ int32_t ALERT_Flush(TLS_Ctx *ctx); /** * @brief Process alert message after decryption * * @attention ctx cannot be empty. * @param ctx [IN] tls Context * @param data [IN] alert data * @param dataLen [IN] alert data length * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG */ int32_t ProcessDecryptedAlert(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen); /** * @brief Process plaintext alert message in TLS13 * * @attention ctx cannot be empty. * @param ctx [IN] tls Context * @param data [IN] alert data * @param dataLen [IN] alert data length * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG */ int32_t ProcessPlainAlert(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen); /** * @ingroup alert * @brief Clear the number of consecutive received warnings * * @param ctx [IN] tls Context */ void ALERT_ClearWarnCount(TLS_Ctx *ctx); /** * @ingroup alert * @brief Increase the number of alert and check whether it has exceeded the threshold or not * * @param ctx [IN] tls Context * @param threshold [IN] alert number threshold * @retval the number of alert has exceeded the threshold or not */ bool ALERT_HaveExceeded(TLS_Ctx *ctx, uint8_t threshold); #ifdef HITLS_BSL_LOG int32_t ReturnAlertProcess(TLS_Ctx *ctx, int32_t err, uint32_t logId, const void *logStr, ALERT_Description description); #define RETURN_ALERT_PROCESS(ctx, err, logId, logStr, description) \ ReturnAlertProcess(ctx, err, logId, LOG_STR(logStr), description) #else #define RETURN_ALERT_PROCESS(ctx, err, logId, logStr, description) \ (ctx)->method.sendAlert(ctx, ALERT_LEVEL_FATAL, description), (err) #endif /* HITLS_BSL_LOG */ #ifdef __cplusplus } #endif #endif /* ALTER_H */
2302_82127028/openHiTLS-examples_5062_4009
tls/alert/include/alert.h
C
unknown
4,799
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_error.h" #include "tls.h" #include "rec.h" #ifdef HITLS_TLS_FEATURE_FLIGHT #include "bsl_uio.h" #include "hitls.h" #endif #include "record.h" #include "alert.h" #define ALERT_DATA_LEN 2u /* alert data length */ /** Alert context, which records the sending and receiving information */ struct AlertCtx { uint8_t flag; /* send and receive flags, for details, see ALERT_FLAG */ bool isFlush; /* whether the message is sent successfully */ uint8_t warnCount; /* count the number of consecutive received warnings */ uint8_t level; /* Alert level. For details, see ALERT_Level */ uint8_t description; /* Alert description: For details, see ALERT_Description */ uint8_t reverse; /* reserve, 4-byte aligned */ }; bool ALERT_GetFlag(const TLS_Ctx *ctx) { return (ctx->alertCtx->flag != ALERT_FLAG_NO); } void ALERT_GetInfo(const TLS_Ctx *ctx, ALERT_Info *info) { struct AlertCtx *alertCtx = ctx->alertCtx; info->flag = alertCtx->flag; info->level = alertCtx->level; info->description = alertCtx->description; return; } void ALERT_CleanInfo(const TLS_Ctx *ctx) { uint8_t alertCount = ctx->alertCtx->warnCount; (void)memset_s(ctx->alertCtx, sizeof(struct AlertCtx), 0, sizeof(struct AlertCtx)); ctx->alertCtx->warnCount = alertCount; return; } /* check whether the operation is abnormal */ bool AlertIsAbnormalInput(const struct AlertCtx *alertCtx, ALERT_Level level) { if (level != ALERT_LEVEL_FATAL && level != ALERT_LEVEL_WARNING) { return true; } if (alertCtx->flag != ALERT_FLAG_NO) { // a critical alert exists and cannot be overwritten if (alertCtx->level == ALERT_LEVEL_FATAL) { return true; } // common alarms are not allowed to overwrite CLOSE NOTIFY if (level == ALERT_LEVEL_WARNING && alertCtx->level == ALERT_LEVEL_WARNING && alertCtx->description == ALERT_CLOSE_NOTIFY) { return true; } } return false; } void ALERT_Send(const TLS_Ctx *ctx, ALERT_Level level, ALERT_Description description) { struct AlertCtx *alertCtx = ctx->alertCtx; // prevent abnormal operations if (AlertIsAbnormalInput(alertCtx, level)) { return; } alertCtx->level = (uint8_t)level; alertCtx->description = (uint8_t)description; alertCtx->flag = ALERT_FLAG_SEND; alertCtx->isFlush = false; return; } int32_t ALERT_Flush(TLS_Ctx *ctx) { struct AlertCtx *alertCtx = ctx->alertCtx; int32_t ret; if (alertCtx->flag != ALERT_FLAG_SEND) { BSL_ERR_PUSH_ERROR(HITLS_ALERT_NO_WANT_SEND); return HITLS_ALERT_NO_WANT_SEND; } #ifdef HITLS_TLS_PROTO_TLS if (REC_GetOutBufPendingSize(ctx) != 0) { ret = REC_OutBufFlush(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #endif if (alertCtx->isFlush == false) { if (ctx->recCtx != NULL && ctx->recCtx->pendingData != NULL && alertCtx->description == ALERT_CLOSE_NOTIFY) { return HITLS_REC_NORMAL_IO_BUSY; } uint8_t data[ALERT_DATA_LEN]; /** obtain the alert level */ data[0] = alertCtx->level; data[1] = alertCtx->description; if (ctx->negotiatedInfo.version == HITLS_VERSION_SSL30 && alertCtx->description == ALERT_PROTOCOL_VERSION) { data[1] = ALERT_HANDSHAKE_FAILURE; } /** write the record */ ret = REC_Write(ctx, REC_TYPE_ALERT, data, ALERT_DATA_LEN); if (!IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { alertCtx->isFlush = true; } if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16267, "Write fail"); } alertCtx->isFlush = true; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15768, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "Sent an Alert msg:level[%u] description[%u]", data[0], data[1], 0, 0); } #ifdef HITLS_TLS_FEATURE_FLIGHT /* if isFlightTransmitEnable is enabled, the stored handshake information needs to be sent */ uint8_t isFlightTransmitEnable = 0; (void)HITLS_GetFlightTransmitSwitch(ctx, &isFlightTransmitEnable); if (isFlightTransmitEnable == 1) { ret = REC_FlightTransmit(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_FLIGHT */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 static uint32_t ALERT_GetVersion(const TLS_Ctx *ctx) { if (ctx->negotiatedInfo.version > 0) { /* the version has been negotiated */ return ctx->negotiatedInfo.version; } else { /* if the version is not negotiated, the latest version supported by the local end is returned */ return ctx->config.tlsConfig.maxVersion; } } #endif /* HITLS_TLS_PROTO_TLS13 */ int32_t ALERT_Init(TLS_Ctx *ctx) { if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15772, 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; } // prevent multi init of ctx->alertCtx if (ctx->alertCtx != NULL) { return HITLS_SUCCESS; } ctx->alertCtx = (struct AlertCtx *)BSL_SAL_Malloc(sizeof(struct AlertCtx)); if (ctx->alertCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15773, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "malloc alert ctx fail.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)memset_s(ctx->alertCtx, sizeof(struct AlertCtx), 0, sizeof(struct AlertCtx)); return HITLS_SUCCESS; } void ALERT_Deinit(TLS_Ctx *ctx) { if (ctx == NULL) { return; } BSL_SAL_FREE(ctx->alertCtx); return; } int32_t ProcessDecryptedAlert(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen) { struct AlertCtx *alertCtx = ctx->alertCtx; /** if the message lengths are not equal, an error code is returned */ if (dataLen != ALERT_DATA_LEN) { BSL_ERR_PUSH_ERROR(HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15769, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a alert msg with illegal len %u", dataLen, 0, 0, 0); ALERT_Send(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } /** record the alert message */ if (data[0] == ALERT_LEVEL_FATAL || data[0] == ALERT_LEVEL_WARNING) { // prevent abnormal operations if (AlertIsAbnormalInput(alertCtx, data[0]) == true) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID16268, "input abnormal"); } alertCtx->flag = ALERT_FLAG_RECV; alertCtx->level = data[0]; alertCtx->description = data[1]; #ifdef HITLS_TLS_PROTO_TLS13 if (ALERT_GetVersion(ctx) == HITLS_VERSION_TLS13 && alertCtx->description != ALERT_CLOSE_NOTIFY) { alertCtx->level = ALERT_LEVEL_FATAL; } #endif if (alertCtx->level == ALERT_LEVEL_FATAL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16269, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "alert fatal", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15770, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "got a alert msg:level[%u] description[%u]", data[0], data[1], 0, 0); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } BSL_ERR_PUSH_ERROR(HITLS_REC_NORMAL_RECV_UNEXPECT_MSG); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15771, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get a alert msg with illegal type", 0, 0, 0, 0); /** Decoding error. Send an alert. */ ALERT_Send(ctx, ALERT_LEVEL_FATAL, ALERT_ILLEGAL_PARAMETER); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t ProcessPlainAlert(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen) { if (ctx->isClient == true && REC_HaveReadSuiteInfo(ctx)) { return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID16270, "receive plain alert", ALERT_UNEXPECTED_MESSAGE); } if (ctx->isClient == false && ctx->plainAlertForbid == true) { return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID16271, "tls1.3 forbid to receive plain alert", ALERT_UNEXPECTED_MESSAGE); } return ProcessDecryptedAlert(ctx, data, dataLen); } #endif /* HITLS_TLS_PROTO_TLS13 */ void ALERT_ClearWarnCount(TLS_Ctx *ctx) { ctx->alertCtx->warnCount = 0; return; } bool ALERT_HaveExceeded(TLS_Ctx *ctx, uint8_t threshold) { ctx->alertCtx->warnCount += 1; return ctx->alertCtx->warnCount >= threshold; } #ifdef HITLS_BSL_LOG int32_t ReturnAlertProcess(TLS_Ctx *ctx, int32_t err, uint32_t logId, const void *logStr, ALERT_Description description) { if (logStr != NULL) { BSL_LOG_BINLOG_FIXLEN(logId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, logStr, 0, 0, 0, 0); } if (description != ALERT_UNKNOWN) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, description); } return err; } int32_t ReturnErrorNumberProcess(int32_t err, uint32_t logId, const void *logStr) { (void)logStr; BSL_LOG_BINLOG_FIXLEN(logId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, logStr, 0, 0, 0, 0); return err; } #endif /* HITLS_BSL_LOG */
2302_82127028/openHiTLS-examples_5062_4009
tls/alert/src/alert.c
C
unknown
10,275
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef APP_H #define APP_H #include <stdint.h> #include "hitls_build.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup app * @brief TLS can read data of any length, not in the unit of record. DTLS can read data in the unit of record. * Reads num bytes from the CTX to the buffer. Users can transfer any num bytes (num must be greater than 0). * * @attention Reads only the application data decrypted by one record at a time. * HITLS copies the application data to the input cache. * If the cache size is less than 16K, the maximum size of the application message decrypted from a single record is 16K * This will result in a partial copy of the application data. * You can call APP_GetReadPendingBytes to obtain the size of the remaining readable application data in current record. * This is useful in DTLS scenarios. * * @param ctx [IN] TLS context * @param buf [OUT] Place the data which read from the TLS context into the buffer. * @param num [IN] Attempting to read num bytes * @param readLen [OUT] Read length * * @retval HITLS_SUCCESS Read successful. * @retval Other return value refers to REC_Read. */ int32_t APP_Read(TLS_Ctx *ctx, uint8_t *buf, uint32_t num, uint32_t *readLen); /** * @ingroup app * @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 Obtain successful. * @retval Other return value refers to REC_GetMaxWriteSize. */ int32_t APP_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len); /** * @ingroup app * @brief Send app message in the unit of record. * * @param ctx [IN] TLS context * @param data [IN] Data to be written * @param dataLen [IN] Data length * @param writeLen [OUT] Length of Successful Writes * * @retval HITLS_SUCCESS Write successful. * @retval HITLS_APP_ERR_TOO_LONG_TO_WRITE The data to be written is too long. * @retval Other reuturn value referst to REC_Write. */ int32_t APP_Write(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/app/include/app.h
C
unknown
2,688
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_uio.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "rec.h" #include "app_ctx.h" #include "rec.h" #include "record.h" #include "app.h" static int32_t ReadAppData(TLS_Ctx *ctx, uint8_t *buf, uint32_t num, uint32_t *readLen) { return REC_Read(ctx, REC_TYPE_APP, buf, readLen, num); } int32_t APP_Read(TLS_Ctx *ctx, uint8_t *buf, uint32_t num, uint32_t *readLen) { int32_t ret; uint32_t readbytes; if (ctx == NULL || buf == NULL || num == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15659, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "APP: input null pointer or read bufLen is 0.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_APP_ERR_ZERO_READ_BUF_LEN); return HITLS_APP_ERR_ZERO_READ_BUF_LEN; } // read data to the buffer in non-blocking mode do { ret = ReadAppData(ctx, buf, num, &readbytes); if (ret != HITLS_SUCCESS) { return ret; } } while (readbytes == 0); // do not exit the loop until data is read *readLen = readbytes; return HITLS_SUCCESS; } int32_t APP_GetMaxWriteSize(const TLS_Ctx *ctx, uint32_t *len) { return REC_GetMaxWriteSize(ctx, len); } static int32_t SavePendingData(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen) { #ifdef HITLS_TLS_PROTO_DTLS if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { return HITLS_SUCCESS; } #endif RecCtx *recCtx = (RecCtx *)ctx->recCtx; // Stores the plaintext data to be sent. recCtx->pendingData = data; recCtx->pendingDataSize = dataLen; return HITLS_SUCCESS; } static int32_t CheckDataLen(TLS_Ctx *ctx, const uint8_t *data, uint32_t *sendLen) { RecCtx *recCtx = (RecCtx *)ctx->recCtx; if (recCtx->pendingData != NULL) { if (( #ifdef HITLS_TLS_FEATURE_MODE_ACCEPT_MOVING_WRITE_BUFFER (ctx->config.tlsConfig.modeSupport & HITLS_MODE_ACCEPT_MOVING_WRITE_BUFFER) == 0 && #endif recCtx->pendingData != data) || recCtx->pendingDataSize > *sendLen) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16241, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "The two buffer addresses are inconsistent.", 0, 0, 0, 0); return HITLS_APP_ERR_WRITE_BAD_RETRY; } *sendLen = recCtx->pendingDataSize; return HITLS_SUCCESS; } uint32_t maxWriteLen = 0u; int32_t ret = REC_GetMaxWriteSize(ctx, &maxWriteLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15660, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "APP: Get record max write size fail.", 0, 0, 0, 0); return ret; } if (*sendLen > maxWriteLen) { *sendLen = maxWriteLen; } return SavePendingData(ctx, data, *sendLen); } int32_t APP_Write(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { 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 = REC_RecOutBufReSet(ctx); if (ret != HITLS_SUCCESS) { return ret; } uint32_t sendLen = dataLen; ret = CheckDataLen(ctx, data, &sendLen); if (ret != HITLS_SUCCESS) { return ret; } *writeLen = 0; ret = REC_Write(ctx, REC_TYPE_APP, data, sendLen); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16274, "Write fail"); } #ifdef HITLS_TLS_FEATURE_FLIGHT if (ctx->config.tlsConfig.isFlightTransmitEnable) { ret = REC_FlightTransmit(ctx); if (ret != HITLS_SUCCESS) { return ret; } } #endif *writeLen = sendLen; ctx->recCtx->pendingData = NULL; ctx->recCtx->pendingDataSize = 0; return HITLS_SUCCESS; }
2302_82127028/openHiTLS-examples_5062_4009
tls/app/src/app.c
C
unknown
4,663
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef APP_CTX_H #define APP_CTX_H #include <stdint.h> #include "hitls_build.h" #ifdef __cplusplus extern "C" { #endif #ifdef HITLS_TLS_FEATURE_RENEGOTIATION /** * @ingroup hitls_cert_type * @brief Describe the APP cache linked list. */ typedef struct BslList AppList; #endif typedef struct { uint8_t *buf; /* buffer */ uint32_t bufSize; /* size of the buffer */ uint32_t start; /* start position */ uint32_t end; /* end position */ } AppBuf; #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/app/src/app_ctx.h
C
unknown
1,066
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CHANGE_CIPHER_SPEC_H #define CHANGE_CIPHER_SPEC_H #include <stdint.h> #include "hitls_build.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @ingroup change cipher spec * @brief CCS initialization function * * @param ctx [IN] SSL context * * @retval HITLS_SUCCESS Initializition successful. * @retval HITLS_INTERNAL_EXCEPTION An unexpected internal error occurs. * @retval HITLS_MEMALLOC_FAIL Failed to apply for memory. */ int32_t CCS_Init(TLS_Ctx *ctx); /** * @ingroup change cipher spec * @brief CCS deinitialization function * * @param ctx [IN] ssl context * */ void CCS_DeInit(TLS_Ctx *ctx); /** * @ingroup change cipher spec * @brief Check whether the Change cipher spec message is received. * * @param ctx [IN] TLS context * * @retval True if the Change cipher spec message is received else false. */ bool CCS_IsRecv(const TLS_Ctx *ctx); /** * @ingroup change cipher spec * @brief Send a packet for changing the cipher suite. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS Send successful. * @retval HITLS_INTERNAL_EXCEPTION An unexpected internal error occurs. * @retval For other error codes, see REC_Write. */ int32_t CCS_Send(TLS_Ctx *ctx); /** * @ingroup change cipher spec * @brief Control function * * @param ctx [IN] TLS context * @param cmd [IN] Control command * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_INTERNAL_EXCEPTION An unexpected internal error * @retval HITLS_CCS_INVALID_CMD Invalid instruction */ int32_t CCS_Ctrl(TLS_Ctx *ctx, CCS_Cmd cmd); /** * @brief Process CCS message after decryption * * @attention ctx cannot be empty. * @param ctx [IN] tls Context * @param data [IN] ccs data * @param dataLen [IN] ccs data length * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG */ int32_t ProcessDecryptedCCS(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen); /** * @brief Process plaintext CCS message in TLS13 * * @attention ctx cannot be empty. * @param ctx [IN] tls Context * @param data [IN] ccs data * @param dataLen [IN] ccs data length * @retval HITLS_REC_NORMAL_RECV_UNEXPECT_MSG */ int32_t ProcessPlainCCS(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/ccs/include/change_cipher_spec.h
C
unknown
2,864
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_error.h" #include "bsl_uio.h" #include "uio_base.h" #include "rec.h" #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif #include "hs.h" #include "alert.h" #include "change_cipher_spec.h" struct CcsCtx { bool isReady; /* Whether to allow receiving CCS */ bool ccsRecvflag; /* Indicates whether the CCS is received. */ bool isAllowActiveCipher; /* Flag for allow activating the receiving key suite */ bool activeCipherFlag; /* Flag for activating the receiving key suite */ }; bool CCS_IsRecv(const TLS_Ctx *ctx) { return ctx->ccsCtx->ccsRecvflag; } int32_t CCS_Send(TLS_Ctx *ctx) { int32_t ret; const uint8_t buf[1] = {1u}; const uint32_t len = 1u; if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15616, 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 defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_SCTP) && defined(HITLS_TLS_FEATURE_RENEGOTIATION) /* rfc6083 4.7. Handshake Before sending a ChangeCipherSpec message, all outstanding SCTP user messages MUST have been acknowledged by the SCTP peer and MUST NOT be revoked by the SCTP peer. */ if (BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_SCTP) && ctx->negotiatedInfo.isRenegotiation) { bool isBuffEmpty = false; ret = BSL_UIO_Ctrl(ctx->uio, BSL_UIO_SCTP_SND_BUFF_IS_EMPTY, (int32_t)sizeof(isBuffEmpty), &isBuffEmpty); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16275, 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; } /* When the SCTP sending buffer is not empty, the CCS cannot be sent. */ if (isBuffEmpty != true) { BSL_ERR_PUSH_ERROR(HITLS_REC_NORMAL_IO_BUSY); return HITLS_REC_NORMAL_IO_BUSY; } } #endif /** Write record */ ret = REC_Write(ctx, REC_TYPE_CHANGE_CIPHER_SPEC, buf, len); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16276, "Write fail"); } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { ret = REC_RetransmitListAppend(ctx->recCtx, REC_TYPE_CHANGE_CIPHER_SPEC, buf, len); if (ret != HITLS_SUCCESS) { return ret; } } #endif #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(1, HS_GetVersion(ctx), REC_TYPE_CHANGE_CIPHER_SPEC, buf, 1, ctx, ctx->config.tlsConfig.msgArg); #endif BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15617, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "written a change cipher spec message.", 0, 0, 0, 0); return HITLS_SUCCESS; } int32_t CCS_Ctrl(TLS_Ctx *ctx, CCS_Cmd cmd) { if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15618, 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; } switch (cmd) { case CCS_CMD_RECV_READY: ctx->ccsCtx->isReady = true; break; case CCS_CMD_RECV_EXIT_READY: ctx->ccsCtx->isReady = false; ctx->ccsCtx->ccsRecvflag = false; ctx->ccsCtx->isAllowActiveCipher = false; ctx->ccsCtx->activeCipherFlag = false; break; case CCS_CMD_RECV_ACTIVE_CIPHER_SPEC: ctx->ccsCtx->isAllowActiveCipher = true; if (ctx->ccsCtx->ccsRecvflag == true && ctx->ccsCtx->activeCipherFlag == false) { /** Enable key specification */ int32_t ret = REC_ActivePendingState(ctx, false); if (ret != HITLS_SUCCESS) { ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } ctx->ccsCtx->activeCipherFlag = true; } break; default: BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15619, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ChangeCipherSpec error ctrl cmd", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CCS_INVALID_CMD); return HITLS_CCS_INVALID_CMD; } return HITLS_SUCCESS; } int32_t CCS_Init(TLS_Ctx *ctx) { if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15620, 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; } // Prevent the ctx->ccsCtx from being initialized multiple times. if (ctx->ccsCtx != NULL) { return HITLS_SUCCESS; } ctx->ccsCtx = (struct CcsCtx *)BSL_SAL_Malloc(sizeof(struct CcsCtx)); if (ctx->ccsCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15621, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ccs ctx malloc failed.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)memset_s(ctx->ccsCtx, sizeof(struct CcsCtx), 0, sizeof(struct CcsCtx)); return HITLS_SUCCESS; } void CCS_DeInit(TLS_Ctx *ctx) { if (ctx == NULL) { return; } BSL_SAL_FREE(ctx->ccsCtx); return; } int32_t ProcessPlainCCS(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen) { if (ctx->ccsCtx->isReady == false) { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) if (IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask) && BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { ctx->rwstate = HITLS_READING; return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } #endif return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID15612, "recv unexpected ccs msg", ALERT_UNEXPECTED_MESSAGE); } /** The read length is abnormal. */ if (dataLen != 1u) { return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID15613, "ccs msg length err", ALERT_UNEXPECTED_MESSAGE); } /** Message exception. */ if (data[0] != 1u) { return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID15614, "ccs msg err", ALERT_UNEXPECTED_MESSAGE); } /** Multiple generate ccs messages are received: If UDP transmission is used, ignore the ccs. */ if (ctx->ccsCtx->ccsRecvflag == true && !BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP) && HS_GetVersion(ctx) != HITLS_VERSION_TLS13) { return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID16277, "Multiple generate ccs msg are received", ALERT_UNEXPECTED_MESSAGE); } if (ctx->ccsCtx->isAllowActiveCipher == true && ctx->ccsCtx->activeCipherFlag == false) { /** Enable key specification */ if (REC_ActivePendingState(ctx, false) != HITLS_SUCCESS) { return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID16278, "ActivePendingState err", ALERT_INTERNAL_ERROR); } ctx->ccsCtx->activeCipherFlag = true; } ctx->ccsCtx->ccsRecvflag = true; #ifdef HITLS_TLS_FEATURE_INDICATOR INDICATOR_MessageIndicate(0, HS_GetVersion(ctx), REC_TYPE_CHANGE_CIPHER_SPEC, data, 1, ctx, ctx->config.tlsConfig.msgArg); #endif BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15615, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "got a change cipher spec message.", 0, 0, 0, 0); #ifdef HITLS_TLS_SUITE_CIPHER_CBC ctx->negotiatedInfo.isEncryptThenMacRead = ctx->negotiatedInfo.isEncryptThenMac; #endif return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } int32_t ProcessDecryptedCCS(TLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen) { #ifdef HITLS_TLS_PROTO_TLS13 if (HS_GetVersion(ctx) == HITLS_VERSION_TLS13) { return RETURN_ALERT_PROCESS(ctx, HITLS_REC_NORMAL_RECV_UNEXPECT_MSG, BINLOG_ID15612, "recv encrypted ccs msg", ALERT_UNEXPECTED_MESSAGE); } #endif return ProcessPlainCCS(ctx, data, dataLen); }
2302_82127028/openHiTLS-examples_5062_4009
tls/ccs/src/change_cipher_spec.c
C
unknown
9,066
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "bsl_bytes.h" #include "bsl_list.h" #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_security.h" #include "tls.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "cert_mgr_ctx.h" #include "cert_method.h" #include "cert_mgr.h" #include "cert.h" #include "config_type.h" #include "pack.h" #include "custom_extensions.h" #ifdef HITLS_TLS_FEATURE_SECURITY static int32_t CheckKeySecbits(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, HITLS_CERT_Key *key) { int32_t ret; int32_t secBits = 0; HITLS_Config *config = &ctx->config.tlsConfig; ret = SAL_CERT_KeyCtrl(config, key, CERT_KEY_CTRL_GET_SECBITS, NULL, (void *)&secBits); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16303, "GET_SECBITS fail"); } ret = SECURITY_SslCheck((HITLS_Ctx *)ctx, HITLS_SECURITY_SECOP_EE_KEY, secBits, 0, cert); if (ret != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16304, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SslCheck fail, ret %d", ret, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_EE_KEY_WITH_INSECURE_SECBITS); ctx->method.sendAlert((TLS_Ctx *)ctx, ALERT_LEVEL_FATAL, ALERT_INSUFFICIENT_SECURITY); return HITLS_CERT_ERR_EE_KEY_WITH_INSECURE_SECBITS; } return HITLS_SUCCESS; } #endif CERT_Type CertKeyType2CertType(HITLS_CERT_KeyType keyType) { switch (keyType) { case TLS_CERT_KEY_TYPE_RSA: case TLS_CERT_KEY_TYPE_RSA_PSS: return CERT_TYPE_RSA_SIGN; case TLS_CERT_KEY_TYPE_DSA: return CERT_TYPE_DSS_SIGN; case TLS_CERT_KEY_TYPE_SM2: case TLS_CERT_KEY_TYPE_ECDSA: case TLS_CERT_KEY_TYPE_ED25519: return CERT_TYPE_ECDSA_SIGN; default: break; } return CERT_TYPE_UNKNOWN; } HITLS_CERT_KeyType SAL_CERT_SignScheme2CertKeyType(const HITLS_Ctx *ctx, HITLS_SignHashAlgo signScheme) { const TLS_SigSchemeInfo *info = ConfigGetSignatureSchemeInfo(&ctx->config.tlsConfig, signScheme); if (info == NULL) { return TLS_CERT_KEY_TYPE_UNKNOWN; } return info->keyType; } HITLS_SignHashAlgo SAL_CERT_GetDefaultSignHashAlgo(HITLS_CERT_KeyType keyType) { switch (keyType) { case TLS_CERT_KEY_TYPE_RSA: return CERT_SIG_SCHEME_RSA_PKCS1_SHA1; case TLS_CERT_KEY_TYPE_RSA_PSS: return CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256; case TLS_CERT_KEY_TYPE_DSA: return CERT_SIG_SCHEME_DSA_SHA1; case TLS_CERT_KEY_TYPE_ECDSA: return CERT_SIG_SCHEME_ECDSA_SHA1; case TLS_CERT_KEY_TYPE_ED25519: return CERT_SIG_SCHEME_ED25519; #ifdef HITLS_TLS_PROTO_TLCP11 case TLS_CERT_KEY_TYPE_SM2: return CERT_SIG_SCHEME_SM2_SM3; #endif default: break; } return CERT_SIG_SCHEME_UNKNOWN; } int32_t CheckCertType(CERT_Type expectCertType, HITLS_CERT_KeyType checkedKeyType) { if (expectCertType == CERT_TYPE_UNKNOWN) { /* The certificate type is not specified. This check is not required. */ return HITLS_SUCCESS; } /* Convert the key type to the certificate type. */ CERT_Type checkedCertType = CertKeyType2CertType(checkedKeyType); if (expectCertType != checkedCertType) { BSL_ERR_PUSH_ERROR(HITLS_MSG_HANDLE_UNSUPPORT_CERT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15034, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "unexpect cert: expect cert type = %u, checked key type = %u.", expectCertType, checkedKeyType, 0, 0); return HITLS_MSG_HANDLE_UNSUPPORT_CERT; } return HITLS_SUCCESS; } static bool IsSignSchemeExist(const uint16_t *signSchemeList, uint32_t signSchemeNum, HITLS_SignHashAlgo signScheme) { for (uint32_t i = 0; i < signSchemeNum; i++) { if (signSchemeList[i] == signScheme) { return true; } } return false; } typedef struct { uint32_t baseSignAlgorithmsSize; const uint16_t *baseSignAlgorithms; uint32_t selectSignAlgorithmsSize; const uint16_t *selectSignAlgorithms; } SelectSignAlgorithms; static int32_t CheckSelectSignAlgorithms(TLS_Ctx *ctx, const SelectSignAlgorithms *select, HITLS_CERT_KeyType checkedKeyType, HITLS_CERT_Key *pubkey, bool isNegotiateSignAlgo) { uint32_t baseSignAlgorithmsSize = select->baseSignAlgorithmsSize; const uint16_t *baseSignAlgorithms = select->baseSignAlgorithms; uint32_t selectSignAlgorithmsSize = select->selectSignAlgorithmsSize; const uint16_t *selectSignAlgorithms = select->selectSignAlgorithms; const TLS_SigSchemeInfo *info = NULL; (void)pubkey; #ifdef HITLS_TLS_PROTO_TLS13 int32_t paraId = 0; (void)SAL_CERT_KeyCtrl(&ctx->config.tlsConfig, pubkey, CERT_KEY_CTRL_GET_PARAM_ID, NULL, (void *)&paraId); #endif for (uint32_t i = 0; i < baseSignAlgorithmsSize; i++) { info = ConfigGetSignatureSchemeInfo(&ctx->config.tlsConfig, baseSignAlgorithms[i]); if (info == NULL || info->keyType != (int32_t)checkedKeyType) { continue; } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13 && info->paraId != 0 && info->paraId != paraId) { continue; } #endif if (!IsSignSchemeExist(selectSignAlgorithms, selectSignAlgorithmsSize, baseSignAlgorithms[i])) { /* The signature algorithm must be the same as the algorithm configured on the peer end. */ continue; } #ifdef HITLS_TLS_FEATURE_SECURITY if (SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_SIGALG_CHECK, 0, baseSignAlgorithms[i], NULL) != SECURITY_SUCCESS) { continue; } #endif if (!isNegotiateSignAlgo) { /* Only the signature algorithm in the certificate is checked. The signature algorithm in the handshake message is not negotiated. */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 const uint32_t rsaPkcsv15Mask = 0x01; const uint32_t dsaMask = 0x02; const uint32_t sha1Mask = 0x0200; const uint32_t sha224Mask = 0x0300; /* rfc8446 4.2.3. Signature Algorithms */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { if (((baseSignAlgorithms[i] & 0xff) == rsaPkcsv15Mask) || ((baseSignAlgorithms[i] & 0xff) == dsaMask) || ((baseSignAlgorithms[i] & 0xff00) == sha1Mask) || ((baseSignAlgorithms[i] & 0xff00) == sha224Mask)) { /* not defined for use in signed TLS handshake messages in TLS1.3 */ continue; } } #endif ctx->negotiatedInfo.signScheme = baseSignAlgorithms[i]; return HITLS_SUCCESS; } BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15981, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "unexpect cert: no available signature scheme, key type = %u.", checkedKeyType, 0, 0, 0); return HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH; } static int32_t CheckSignScheme(TLS_Ctx *ctx, const uint16_t *signSchemeList, uint32_t signSchemeNum, HITLS_CERT_KeyType checkedKeyType, HITLS_CERT_Key *pubkey, bool isNegotiateSignAlgo) { if (signSchemeList == NULL) { if (!isNegotiateSignAlgo) { /* Do not save the signature algorithm used for sending handshake messages. */ return HITLS_SUCCESS; } /* No signature algorithm is specified. The default signature algorithm is used when handshake messages are sent. */ HITLS_SignHashAlgo signScheme = SAL_CERT_GetDefaultSignHashAlgo(checkedKeyType); if (signScheme == CERT_SIG_SCHEME_UNKNOWN #ifdef HITLS_TLS_FEATURE_SECURITY || SECURITY_SslCheck(ctx, HITLS_SECURITY_SECOP_SIGALG_CHECK, 0, signScheme, NULL) != SECURITY_SUCCESS #endif ) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16074, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "unexpect key type: no available signature scheme, key type = %u.", checkedKeyType, 0, 0, 0); return HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH; } ctx->negotiatedInfo.signScheme = signScheme; return HITLS_SUCCESS; } SelectSignAlgorithms select = { 0 }; bool supportServer = ctx->config.tlsConfig.isSupportServerPreference; select.baseSignAlgorithmsSize = supportServer ? ctx->config.tlsConfig.signAlgorithmsSize : signSchemeNum; select.baseSignAlgorithms = supportServer ? ctx->config.tlsConfig.signAlgorithms : signSchemeList; select.selectSignAlgorithmsSize = supportServer ? signSchemeNum : ctx->config.tlsConfig.signAlgorithmsSize; select.selectSignAlgorithms = supportServer ? signSchemeList : ctx->config.tlsConfig.signAlgorithms; return CheckSelectSignAlgorithms(ctx, &select, checkedKeyType, pubkey, isNegotiateSignAlgo); } int32_t CheckCurveName(HITLS_Config *config, const uint16_t *curveList, uint32_t curveNum, HITLS_CERT_Key *pubkey) { uint32_t curveName = HITLS_NAMED_GROUP_BUTT; int32_t ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_CURVE_NAME, NULL, (void *)&curveName); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15036, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "internal error: unable to get curve name.", 0, 0, 0, 0); return ret; } for (uint32_t i = 0; i < curveNum; i++) { if (curveName == curveList[i]) { return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_NO_CURVE_MATCH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15037, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "unexpect cert: no curve match, which used %u.", curveName, 0, 0, 0); return HITLS_CERT_ERR_NO_CURVE_MATCH; } int32_t CheckPointFormat(HITLS_Config *config, const uint8_t *ecPointFormatList, uint32_t listSize, HITLS_CERT_Key *pubkey) { uint32_t ecPointFormat = HITLS_POINT_FORMAT_BUTT; int32_t ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_POINT_FORMAT, NULL, (void *)&ecPointFormat); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15038, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "internal error: unable to get point format.", 0, 0, 0, 0); return ret; } for (uint32_t i = 0; i < listSize; i++) { if (ecPointFormat == ecPointFormatList[i]) { return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_NO_POINT_FORMAT_MATCH); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15039, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "unexpect cert: no point format match, which used %u.", ecPointFormat, 0, 0, 0); return HITLS_CERT_ERR_NO_POINT_FORMAT_MATCH; } int32_t IsEcParamCompatible(HITLS_Config *config, const CERT_ExpectInfo *info, HITLS_CERT_Key *pubkey) { int32_t ret; /* If the client has used a Supported Elliptic Curves Extension, the public key in the server's certificate MUST respect the client's choice of elliptic curves */ if (info->ellipticCurveNum != 0) { ret = CheckCurveName(config, info->ellipticCurveList, info->ellipticCurveNum, pubkey); if (ret != HITLS_SUCCESS) { return ret; } } if (info->ecPointFormatNum != 0) { ret = CheckPointFormat(config, info->ecPointFormatList, info->ecPointFormatNum, pubkey); if (ret != HITLS_SUCCESS) { return ret; } } return HITLS_SUCCESS; } static int32_t CheckCertTypeAndSignScheme(HITLS_Ctx *ctx, const CERT_ExpectInfo *expectCertInfo, HITLS_CERT_Key *pubkey, bool isNegotiateSignAlgo, bool signCheck) { HITLS_Config *config = &ctx->config.tlsConfig; uint32_t keyType = TLS_CERT_KEY_TYPE_UNKNOWN; int32_t ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_TYPE, NULL, (void *)&keyType); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15041, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "check certificate error: pubkey type unknown.", 0, 0, 0, 0); return ret; } ret = CheckCertType(expectCertInfo->certType, keyType); if (ret != HITLS_SUCCESS) { return ret; } if (signCheck == true) { ret = CheckSignScheme(ctx, expectCertInfo->signSchemeList, expectCertInfo->signSchemeNum, keyType, pubkey, isNegotiateSignAlgo); if (ret != HITLS_SUCCESS) { return ret; } } /* ECDSA certificate. The curve ID and point format must be checked. TLS_CERT_KEY_TYPE_SM2 does not check the curve ID and point format. TLCP curves is sm2 and is not compressed. */ if (keyType == TLS_CERT_KEY_TYPE_ECDSA && ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { ret = IsEcParamCompatible(config, expectCertInfo, pubkey); } return ret; } int32_t SAL_CERT_CheckCertInfo(HITLS_Ctx *ctx, const CERT_ExpectInfo *expectCertInfo, HITLS_CERT_X509 *cert, bool isNegotiateSignAlgo, bool signCheck) { HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *mgrCtx = config->certMgrCtx; HITLS_CERT_Key *pubkey = NULL; int32_t ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID15040, "get pubkey fail"); } do { #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckKeySecbits(ctx, cert, pubkey); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16307, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckKeySecbits fail", 0, 0, 0, 0); break; } #endif ret = CheckCertTypeAndSignScheme(ctx, expectCertInfo, pubkey, isNegotiateSignAlgo, signCheck); if (ret != HITLS_SUCCESS) { break; } } while (false); SAL_CERT_KeyFree(mgrCtx, pubkey); return ret; } /* * Server: Currently, two certificates are required for either of the two cipher suites supported. * If the ECDHE cipher suite is used, the client needs to obtain the encrypted certificate to generate the premaster key * and the signature certificate authenticates the identity. * If the ECC cipher suite is used, the server public key is required to encrypt the premaster key * and the signature certificate authentication is required. * Client: Only the ECDHE cipher suite requires the client encryption certificate. * In this case, the value of isNeedClientCert is true and may not be two-way authentication. (The specific value * depends on the server configuration.) * Therefore, the client does not verify any certificate and only sets the index. * */ #ifdef HITLS_TLS_PROTO_TLCP11 static int32_t TlcpSelectCertByInfo(HITLS_Ctx *ctx, CERT_ExpectInfo *info) { int32_t encCertKeyType = TLS_CERT_KEY_TYPE_SM2; CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)encCertKeyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_SELECT_CERTIFICATE, BINLOG_ID17336, "The certificate required by TLCP is not loaded"); } HITLS_CERT_X509 *cert = certPair->cert; HITLS_CERT_X509 *encCert = certPair->encCert; if (ctx->isClient == false || ctx->negotiatedInfo.cipherSuiteInfo.kxAlg == HITLS_KEY_EXCH_ECDHE) { if (cert == NULL || encCert == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_SELECT_CERTIFICATE, BINLOG_ID15042, "The certificate required by TLCP is not loaded"); } ret = SAL_CERT_CheckCertInfo(ctx, info, cert, true, true); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16308, "CheckCertInfo fail"); } ret = SAL_CERT_CheckCertInfo(ctx, info, encCert, true, false); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16309, "CheckCertInfo fail"); } } else { /* Check whether the certificate is missing when the client sends the certificate or sends it to the server for processing. Check whether the authentication-related signature certificate or derived encryption certificate exists when the client uses the certificate. */ if (cert != NULL) { ret = SAL_CERT_CheckCertInfo(ctx, info, cert, true, true); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16310, "CheckCertInfo fail"); } } if (encCert != NULL) { ret = SAL_CERT_CheckCertInfo(ctx, info, encCert, true, false); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16311, "CheckCertInfo fail"); } } } mgrCtx->currentCertKeyType = TLS_CERT_KEY_TYPE_SM2; return HITLS_SUCCESS; } #endif static int32_t SelectCertByInfo(HITLS_Ctx *ctx, CERT_ExpectInfo *info) { int32_t ret; CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_UNREGISTERED_CALLBACK); return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16312, "unregistered callback"); } BSL_HASH_Hash *certPairs = mgrCtx->certPairs; BSL_HASH_Iterator it = BSL_HASH_IterBegin(certPairs); while (it != BSL_HASH_IterEnd(certPairs)) { uint32_t keyType = (uint32_t)BSL_HASH_HashIterKey(certPairs, it); CERT_Pair *certPair = (CERT_Pair *)BSL_HASH_IterValue(certPairs, it); if (certPair == NULL || certPair->cert == NULL || certPair->privateKey == NULL) { it = BSL_HASH_IterNext(certPairs, it); continue; } ret = SAL_CERT_CheckCertInfo(ctx, info, certPair->cert, true, true); if (ret != HITLS_SUCCESS) { it = BSL_HASH_IterNext(certPairs, it); continue; } /* Find a proper certificate and record the corresponding subscript. */ mgrCtx->currentCertKeyType = keyType; return HITLS_SUCCESS; } return HITLS_CERT_ERR_SELECT_CERTIFICATE; } int32_t SAL_CERT_SelectCertByInfo(HITLS_Ctx *ctx, CERT_ExpectInfo *info) { int32_t ret = HITLS_SUCCESS; CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; if (mgrCtx == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16313, "unregistered callback"); } if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { #ifdef HITLS_TLS_PROTO_TLCP11 ret = TlcpSelectCertByInfo(ctx, info); #endif } else { ret = SelectCertByInfo(ctx, info); } if (ret == HITLS_SUCCESS) { return ret; } BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_SELECT_CERTIFICATE); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16151, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "select certificate fail. ret %d", ret, 0, 0, 0); mgrCtx->currentCertKeyType = TLS_CERT_KEY_TYPE_UNKNOWN; return HITLS_CERT_ERR_SELECT_CERTIFICATE; } int32_t EncodeCertificate(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, PackPacket *pkt, uint32_t certIndex) { if (ctx == NULL || pkt == NULL || cert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16314, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } (void)certIndex; int32_t ret; HITLS_Config *config = &ctx->config.tlsConfig; uint32_t certLen = 0; ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_ENCODE_LEN, NULL, (void *)&certLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15043, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode certificate error: unable to get encode length.", 0, 0, 0, 0); return ret; } if (certLen == 0) { BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_ENCODE_CERT); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15044, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cert encode len is 0", 0, 0, 0, 0); return HITLS_CERT_ERR_ENCODE_CERT; } /* Write the length of the certificate data (3 bytes). */ ret = PackAppendUint24ToBuf(pkt, certLen); if (ret != HITLS_SUCCESS) { return ret; } /* Reserve space for certificate data and encode directly */ uint8_t *certBuf = NULL; ret = PackReserveBytes(pkt, certLen, &certBuf); if (ret != HITLS_SUCCESS) { return ret; } uint32_t usedLen = 0; /* Write the certificate data using the low-level encoding function */ ret = SAL_CERT_X509Encode(ctx, cert, certBuf, certLen, &usedLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16315, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "X509Encode err", 0, 0, 0, 0); return ret; } ret = PackSkipBytes(pkt, usedLen); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_PROTO_TLS13 if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { /* If an extension applies to the entire chain, it SHOULD be included in the first CertificateEntry. */ /* Start length field for extensions */ uint32_t exLenPos = 0; ret = PackStartLengthField(pkt, sizeof(uint16_t), &exLenPos); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION if (IsPackNeedCustomExtensions(CUSTOM_EXT_FROM_CTX(ctx), HITLS_EX_TYPE_TLS1_3_CERTIFICATE)) { ret = PackCustomExtensions(ctx, pkt, HITLS_EX_TYPE_TLS1_3_CERTIFICATE, cert, certIndex); if (ret != HITLS_SUCCESS) { return ret; } } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ /* Close extension length field */ PackCloseUint16Field(pkt, exLenPos); } #endif return HITLS_SUCCESS; } void FreeCertList(HITLS_CERT_X509 **certList, uint32_t certNum) { if (certList == NULL) { return; } for (uint32_t i = 0; i < certNum; i++) { SAL_CERT_X509Free(certList[i]); } } static int32_t EncodeEECert(HITLS_Ctx *ctx, PackPacket *pkt, HITLS_CERT_X509 **cert) { CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; CERT_Pair *currentCertPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)mgrCtx->currentCertKeyType, (uintptr_t *)&currentCertPair); if (ret != HITLS_SUCCESS || currentCertPair == NULL || currentCertPair->cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_EXP_CERT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_EXP_CERT, BINLOG_ID16152, "first cert is null"); } HITLS_CERT_X509 *tmpCert = currentCertPair->cert; #ifdef HITLS_TLS_FEATURE_SECURITY HITLS_CERT_Key *key = currentCertPair->privateKey; ret = CheckKeySecbits(ctx, tmpCert, key); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16317, "check key fail"); } #endif /* Write the first device certificate. */ ret = EncodeCertificate(ctx, tmpCert, pkt, 0); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16153, "encode fail"); } #ifdef HITLS_TLS_PROTO_TLCP11 /* If the TLCP algorithm is used and the encryption certificate is required, write the second encryption certificate. */ HITLS_CERT_X509 *certEnc = currentCertPair->encCert; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11 && certEnc != NULL) { #ifdef HITLS_TLS_FEATURE_SECURITY HITLS_CERT_Key *keyEnc = currentCertPair->encPrivateKey; ret = CheckKeySecbits(ctx, certEnc, keyEnc); if (ret != HITLS_SUCCESS) { return ret; } #endif ret = EncodeCertificate(ctx, certEnc, pkt, 1); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16154, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "TLCP encode device certificate error.", 0, 0, 0, 0); return ret; } } #endif *cert = tmpCert; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SECURITY static int32_t CheckCertChainFromStore(HITLS_Config *config, HITLS_CERT_X509 *cert) { HITLS_CERT_Key *pubkey = NULL; CERT_MgrCtx *mgrCtx = config->certMgrCtx; int32_t ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CFG_ERR_LOAD_CERT_FILE, BINLOG_ID16318, "GET_PUB_KEY fail"); } int32_t secBits = 0; ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_SECBITS, NULL, (void *)&secBits); SAL_CERT_KeyFree(mgrCtx, pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16319, "GET_SECBITS fail"); } ret = SECURITY_CfgCheck(config, HITLS_SECURITY_SECOP_CA_KEY, secBits, 0, cert); // cert key if (ret != SECURITY_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16320, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CfgCheck fail, ret %d", ret, 0, 0, 0); return HITLS_CERT_ERR_CA_KEY_WITH_INSECURE_SECBITS; } int32_t signAlg = 0; ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_SIGN_ALGO, NULL, (void *)&signAlg); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16321, "GET_SIGN_ALGO fail"); } ret = SECURITY_CfgCheck(config, HITLS_SECURITY_SECOP_SIGALG_CHECK, 0, signAlg, NULL); if (ret != SECURITY_SUCCESS) { return HITLS_CERT_ERR_INSECURE_SIG_ALG ; } return HITLS_SUCCESS; } #endif static int32_t EncodeCertificateChain(HITLS_Ctx *ctx, PackPacket *pkt) { HITLS_CERT_X509 *tempCert = NULL; HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *mgrCtx = config->certMgrCtx; CERT_Pair *currentCertPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)mgrCtx->currentCertKeyType, (uintptr_t *)&currentCertPair); if (ret != HITLS_SUCCESS || currentCertPair == NULL) { return HITLS_SUCCESS; } HITLS_CERT_Chain *chain = NULL; if (BSL_LIST_COUNT(currentCertPair->chain) > 0) { chain = currentCertPair->chain; } else { chain = mgrCtx->extraChain; } tempCert = (HITLS_CERT_X509 *)BSL_LIST_GET_FIRST(chain); uint32_t certIndex = 1; while (tempCert != NULL) { ret = EncodeCertificate(ctx, tempCert, pkt, certIndex); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID15048, "encode cert chain err"); } certIndex++; tempCert = BSL_LIST_GET_NEXT(chain); } return HITLS_SUCCESS; } static int32_t EncodeCertStore(HITLS_Ctx *ctx, PackPacket *pkt, HITLS_CERT_X509 *cert) { HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *mgrCtx = config->certMgrCtx; HITLS_CERT_Store *store = (mgrCtx->chainStore != NULL) ? mgrCtx->chainStore : mgrCtx->certStore; HITLS_CERT_X509 *certList[TLS_DEFAULT_VERIFY_DEPTH] = {0}; uint32_t certNum = TLS_DEFAULT_VERIFY_DEPTH; if (store != NULL) { int32_t ret = SAL_CERT_BuildChain(config, store, cert, certList, &certNum); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16322, "BuildChain fail"); } /* The first device certificate has been written. The certificate starts from the second one. */ for (uint32_t i = 1; i < certNum; i++) { #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertChainFromStore(config, certList[i]); if (ret != HITLS_SUCCESS) { FreeCertList(certList, certNum); return ret; } #endif ret = EncodeCertificate(ctx, certList[i], pkt, i); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16155, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode cert chain error in No.%u.", i, 0, 0, 0); FreeCertList(certList, certNum); return ret; } } } FreeCertList(certList, certNum); return HITLS_SUCCESS; } /* * The constructed certificate chain is incomplete (excluding the root certificate). * Therefore, in the buildCertChain callback, the return value is ignored, even if the error returned by this call. * In fact, certificates are not verified but chains are constructed as many as possible. * So do not need to invoke buildCertChain if the certificate is encrypted using the TLCP. * If the TLCP is used, the server has checked that the two certificates are not empty. * The client does not check, the message is sent based on the configuration. * If the message will be sent, the signature certificate must exist. * */ int32_t SAL_CERT_EncodeCertChain(HITLS_Ctx *ctx, PackPacket *pkt) { if (ctx == NULL || pkt == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID16323, "input null"); } HITLS_CERT_X509 *cert = NULL; HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16324, "unregistered callback"); } CERT_Pair *currentCertPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)mgrCtx->currentCertKeyType, (uintptr_t *)&currentCertPair); if (ret != HITLS_SUCCESS || currentCertPair == NULL) { /* No certificate needs to be sent at the local end. */ return HITLS_SUCCESS; } ret = EncodeEECert(ctx, pkt, &cert); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID15046, "encode device cert err"); } // Check the size. If a certificate exists in the chain, directly put the data in the chain into the buf and return. if (BSL_LIST_COUNT(currentCertPair->chain) > 0 || BSL_LIST_COUNT(mgrCtx->extraChain) > 0) { return EncodeCertificateChain(ctx, pkt); } return EncodeCertStore(ctx, pkt, cert); } #ifdef HITLS_TLS_PROTO_TLS13 // rfc8446 4.4.2.4. Receiving a Certificate Message // Any endpoint receiving any certificate which it would need to validate using any signature algorithm using an MD5 // hash MUST abort the handshake with a "bad_certificate" alert. // Currently, the MD5 signature algorithm is not available, but it is still an unknown one. int32_t CheckCertSignature(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert) { HITLS_Config *config = &ctx->config.tlsConfig; if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { HITLS_SignHashAlgo signAlg = CERT_SIG_SCHEME_UNKNOWN; const uint32_t md5Mask = 0x0100; (void)SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_SIGN_ALGO, NULL, (void *)&signAlg); if ((signAlg == CERT_SIG_SCHEME_UNKNOWN) || (((uint32_t)signAlg & 0xff00) == md5Mask)) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_CTRL_ERR_GET_SIGN_ALGO, BINLOG_ID16325, "signAlg unknow"); } } return HITLS_SUCCESS; } #endif static void DestoryParseChain(HITLS_CERT_X509 *encCert, HITLS_CERT_X509 *cert, HITLS_CERT_Chain *newChain) { SAL_CERT_X509Free(encCert); SAL_CERT_X509Free(cert); SAL_CERT_ChainFree(newChain); } #ifdef HITLS_TLS_PROTO_TLCP11 static bool TlcpCheckSignCertKeyUsage(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert) { if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { return SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE) || SAL_CERT_CheckCertKeyUsage(ctx, cert, CERT_KEY_CTRL_IS_NON_REPUDIATION_USAGE); } return true; } static bool TlcpCheckEncCertKeyUsage(HITLS_Ctx *ctx, HITLS_CERT_X509 *encCert) { if (ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11) { return SAL_CERT_CheckCertKeyUsage(ctx, encCert, CERT_KEY_CTRL_IS_KEYENC_USAGE) || SAL_CERT_CheckCertKeyUsage(ctx, encCert, CERT_KEY_CTRL_IS_DATA_ENC_USAGE) || SAL_CERT_CheckCertKeyUsage(ctx, encCert, CERT_KEY_CTRL_IS_KEY_AGREEMENT_USAGE); } return false; } #endif int32_t ParseChain(HITLS_Ctx *ctx, CERT_Item *item, HITLS_CERT_Chain **chain, HITLS_CERT_X509 **encCert) { if (ctx == NULL || chain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID16326, "input null"); } HITLS_CERT_X509 *encCertLocal = NULL; HITLS_Config *config = &ctx->config.tlsConfig; HITLS_CERT_Chain *newChain = SAL_CERT_ChainNew(); if (newChain == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID15049, "ChainNew fail"); } CERT_Item *listNode = item; while (listNode != NULL) { HITLS_CERT_X509 *cert = SAL_CERT_X509Parse(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, listNode->data, listNode->dataSize, TLS_PARSE_TYPE_BUFF, TLS_PARSE_FORMAT_ASN1); if (cert == NULL) { DestoryParseChain(encCertLocal, NULL, newChain); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_PARSE_MSG, BINLOG_ID15050, "parse cert chain err"); } #ifdef HITLS_TLS_PROTO_TLS13 if (CheckCertSignature(ctx, cert) != HITLS_SUCCESS) { DestoryParseChain(encCertLocal, cert, newChain); return HITLS_CERT_CTRL_ERR_GET_SIGN_ALGO; } #endif #ifdef HITLS_TLS_PROTO_TLCP11 if ((encCert != NULL) && (TlcpCheckEncCertKeyUsage(ctx, cert) == true)) { SAL_CERT_X509Free(encCertLocal); encCertLocal = cert; listNode = listNode->next; continue; } #endif /* Add a certificate to the certificate chain. */ if (SAL_CERT_ChainAppend(newChain, cert) != HITLS_SUCCESS) { DestoryParseChain(encCertLocal, cert, newChain); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID15051, "ChainAppend fail"); } listNode = listNode->next; } if (encCert != NULL) { *encCert = encCertLocal; } *chain = newChain; return HITLS_SUCCESS; } int32_t SAL_CERT_ParseCertChain(HITLS_Ctx *ctx, CERT_Item *item, CERT_Pair **certPair) { if (ctx == NULL || item == NULL || certPair == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID16327, "input null"); } HITLS_CERT_X509 *encCert = NULL; HITLS_Config *config = &ctx->config.tlsConfig; if (config->certMgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_UNREGISTERED_CALLBACK); return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16328, "unregistered callback"); } /* Parse the first device certificate. */ HITLS_CERT_X509 *cert = SAL_CERT_X509Parse(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, item->data, item->dataSize, TLS_PARSE_TYPE_BUFF, TLS_PARSE_FORMAT_ASN1); if (cert == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_PARSE_MSG, BINLOG_ID15052, "X509Parse fail"); } #ifdef HITLS_TLS_PROTO_TLS13 if (CheckCertSignature(ctx, cert) != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_CTRL_ERR_GET_SIGN_ALGO, BINLOG_ID16329, "check signature fail"); } #endif #ifdef HITLS_TLS_PROTO_TLCP11 if (!TlcpCheckSignCertKeyUsage(ctx, cert)) { SAL_CERT_X509Free(cert); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_KEYUSAGE, BINLOG_ID15341, "check sign cert keyusage fail"); } #endif /* Parse other certificates in the certificate chain. */ HITLS_CERT_Chain *chain = NULL; HITLS_CERT_X509 **inParseEnc = ctx->negotiatedInfo.version == HITLS_VERSION_TLCP_DTLCP11 ? &encCert : NULL; int32_t ret = ParseChain(ctx, item->next, &chain, inParseEnc); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16330, "ParseChain fail"); } CERT_Pair *newCertPair = BSL_SAL_Calloc(1u, sizeof(CERT_Pair)); if (newCertPair == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); SAL_CERT_X509Free(cert); SAL_CERT_X509Free(encCert); SAL_CERT_ChainFree(chain); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID15053, "Calloc fail"); } newCertPair->cert = cert; #ifdef HITLS_TLS_PROTO_TLCP11 newCertPair->encCert = encCert; #endif newCertPair->chain = chain; *certPair = newCertPair; return HITLS_SUCCESS; } int32_t SAL_CERT_VerifyCertChain(HITLS_Ctx *ctx, CERT_Pair *certPair, bool isTlcpEncCert) { (void)isTlcpEncCert; if (ctx == NULL || certPair == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID16331, "input null"); } int32_t ret; uint32_t i = 0; HITLS_Config *config = &ctx->config.tlsConfig; CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_UNREGISTERED_CALLBACK); return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16332, "mgrCtx null"); } HITLS_CERT_Chain *chain = certPair->chain; /* Obtain the number of certificates. The first device certificate must also be included. */ uint32_t certNum = (uint32_t)(BSL_LIST_COUNT(chain) + 1); HITLS_CERT_X509 **certList = (HITLS_CERT_X509 **)BSL_SAL_Calloc(1u, sizeof(HITLS_CERT_X509 *) * certNum); if (certList == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID15054, "Calloc fail"); } certList[i++] = #ifdef HITLS_TLS_PROTO_TLCP11 isTlcpEncCert ? certPair->encCert : #endif certPair->cert; HITLS_CERT_X509 *currCert = NULL; for (uint32_t index = 0u; index < (certNum - 1); ++index) { currCert = (HITLS_CERT_X509 *)BSL_LIST_GetIndexNode(index, chain); certList[i++] = currCert; } /* Verify the certificate chain. */ HITLS_CERT_Store *store = (mgrCtx->verifyStore != NULL) ? mgrCtx->verifyStore : mgrCtx->certStore; if (store == NULL) { BSL_SAL_FREE(certList); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_VERIFY_CERT_CHAIN, BINLOG_ID16333, "Calloc fail"); } ret = SAL_CERT_VerifyChain(ctx, store, certList, i); BSL_SAL_FREE(certList); return ret; } uint32_t SAL_CERT_GetSignMaxLen(HITLS_Config *config, HITLS_CERT_Key *key) { uint32_t len = 0; int32_t ret = SAL_CERT_KeyCtrl(config, key, CERT_KEY_CTRL_GET_SIGN_LEN, NULL, &len); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15056, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "get signature length error: callback ret = 0x%x.", ret, 0, 0, 0); return 0; } return len; } #ifdef HITLS_TLS_CONFIG_CERT_CALLBACK int32_t HITLS_CFG_SetCheckPriKeyCb(HITLS_Config *config, CERT_CheckPrivateKeyCallBack checkPrivateKey) { if (config == NULL || config->certMgrCtx == NULL || checkPrivateKey == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } #ifndef HITLS_TLS_FEATURE_PROVIDER config->certMgrCtx->method.checkPrivateKey = checkPrivateKey; #endif return HITLS_SUCCESS; } CERT_CheckPrivateKeyCallBack HITLS_CFG_GetCheckPriKeyCb(HITLS_Config *config) { if (config == NULL || config->certMgrCtx == NULL) { return NULL; } #ifndef HITLS_TLS_FEATURE_PROVIDER return config->certMgrCtx->method.checkPrivateKey; #else return NULL; #endif } #endif /* HITLS_TLS_CONFIG_CERT_CALLBACK */ #ifdef HITLS_TLS_PROTO_TLCP11 static uint8_t *EncodeEncCert(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, uint32_t *useLen) { if (ctx == NULL || cert == NULL || useLen == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16336, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return NULL; } uint32_t certLen; HITLS_Config *config = &ctx->config.tlsConfig; int32_t ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_ENCODE_LEN, NULL, (void *)&certLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16157, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode gm enc certificate error: unable to get encode length.", 0, 0, 0, 0); return NULL; } uint8_t *data = BSL_SAL_Calloc(1u, certLen); if (data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16158, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "signature data memory alloc fail.", 0, 0, 0, 0); return NULL; } ret = SAL_CERT_X509Encode(ctx, cert, data, certLen, useLen); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(data); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16232, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encode cert error: callback ret = 0x%x.", (uint32_t)ret, 0, 0, 0); return NULL; } return data; } uint8_t *SAL_CERT_SrvrGmEncodeEncCert(HITLS_Ctx *ctx, uint32_t *useLen) { if (ctx == NULL || useLen == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16337, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return NULL; } int keyType = TLS_CERT_KEY_TYPE_SM2; CERT_MgrCtx *mgrCtx = ctx->config.tlsConfig.certMgrCtx; CERT_Pair *currentCertPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)keyType, (uintptr_t *)&currentCertPair); if (ret != HITLS_SUCCESS || currentCertPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17337, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "encCert null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return NULL; } HITLS_CERT_X509 *cert = currentCertPair->encCert; return EncodeEncCert(ctx, cert, useLen); } uint8_t *SAL_CERT_ClntGmEncodeEncCert(HITLS_Ctx *ctx, CERT_Pair *peerCert, uint32_t *useLen) { return EncodeEncCert(ctx, peerCert->encCert, useLen); } #endif #if defined(HITLS_TLS_PROTO_TLCP11) || defined(HITLS_TLS_CONFIG_KEY_USAGE) bool SAL_CERT_CheckCertKeyUsage(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, HITLS_CERT_CtrlCmd keyusage) { if (ctx == NULL || cert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16338, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } uint8_t isUsage = false; if (keyusage != CERT_KEY_CTRL_IS_KEYENC_USAGE && keyusage != CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE && keyusage != CERT_KEY_CTRL_IS_KEY_CERT_SIGN_USAGE && keyusage != CERT_KEY_CTRL_IS_KEY_AGREEMENT_USAGE && keyusage != CERT_KEY_CTRL_IS_DATA_ENC_USAGE && keyusage != CERT_KEY_CTRL_IS_NON_REPUDIATION_USAGE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16339, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "keyusage err", 0, 0, 0, 0); return (bool)isUsage; } HITLS_Config *config = &ctx->config.tlsConfig; if (SAL_CERT_X509Ctrl(config, cert, keyusage, NULL, (void *)&isUsage) != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16340, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "%d fail", keyusage, 0, 0, 0); return false; } return (bool)isUsage; } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/cert_adapt/cert.c
C
unknown
44,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. */ #include <stdint.h> #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "bsl_list.h" #include "hitls_error.h" #include "cert_method.h" #include "cert_mgr_ctx.h" HITLS_CERT_Chain *SAL_CERT_ChainNew(void) { BslList *newChain = BSL_LIST_New(sizeof(HITLS_CERT_X509 *)); if (newChain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15010, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "new cert chain error: out of memory.", 0, 0, 0, 0); } return newChain; } int32_t SAL_CERT_ChainAppend(HITLS_CERT_Chain *chain, HITLS_CERT_X509 *cert) { /* add the tail to the end of the certificate chain, corresponding to the top of the stack */ int32_t ret = BSL_LIST_AddElement(chain, cert, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15011, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "append cert to chain error: out of memory.", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } static void CertChainInnerDestroyCb(void *cert) { SAL_CERT_X509Free((HITLS_CERT_X509 *)cert); } /* release the linked list without retaining the head node */ void SAL_CERT_ChainFree(HITLS_CERT_Chain *chain) { /* only certificates on the chain are destroyed, chain itself will be not destroyed */ BSL_LIST_DeleteAll(chain, CertChainInnerDestroyCb); BSL_SAL_FREE(chain); return; } /* copy the certificate chain */ HITLS_CERT_Chain *SAL_CERT_ChainDup(CERT_MgrCtx *mgrCtx, HITLS_CERT_Chain *chain) { int32_t ret; uint32_t listSize = (uint32_t)BSL_LIST_COUNT(chain); HITLS_CERT_X509 *dupCert = NULL; HITLS_CERT_X509 *currCert = NULL; if (BSL_LIST_COUNT(chain) < 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16070, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dup cert chain error: list size tainted.", 0, 0, 0, 0); return NULL; } BslList *newChain = SAL_CERT_ChainNew(); if (newChain == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15012, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dup cert chain error: out of memory.", 0, 0, 0, 0); return NULL; } for (uint32_t index = 0u; index < listSize; ++index) { currCert = (HITLS_CERT_X509 *)BSL_LIST_GetIndexNode(index, chain); if (currCert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15002, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dup cert error: currCert NULL.", 0, 0, 0, 0); goto EXIT; } dupCert = SAL_CERT_X509Dup(mgrCtx, currCert); if (dupCert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15013, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dup cert chain error: x509 dup error.", 0, 0, 0, 0); goto EXIT; } ret = SAL_CERT_ChainAppend(newChain, dupCert); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15014, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dup cert chain error: append new cert node error.", 0, 0, 0, 0); SAL_CERT_X509Free(dupCert); goto EXIT; } } return newChain; EXIT: /* free the certificate chain */ SAL_CERT_ChainFree(newChain); return NULL; }
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/cert_adapt/cert_chain.c
C
unknown
3,956
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stddef.h> #include "hitls_build.h" #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_x509_adapt.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "hitls_pki_x509.h" #endif /* HITLS_TLS_FEATURE_PROVIDER */ #include "tls_config.h" #include "tls.h" #include "cert_mgr_ctx.h" #include "cert_method.h" #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_MgrMethod g_certMgrMethod = {0}; static bool IsMethodValid(const HITLS_CERT_MgrMethod *method) { bool valid = method == NULL || method->certStoreNew == NULL || method->certStoreDup == NULL || method->certStoreFree == NULL || method->certStoreCtrl == NULL || method->buildCertChain == NULL || method->verifyCertChain == NULL || method->certEncode == NULL || method->certParse == NULL || method->certDup == NULL || method->certFree == NULL || method->certCtrl == NULL || method->keyParse == NULL || method->keyDup == NULL || method->keyFree == NULL || method->keyCtrl == NULL || method->createSign == NULL || method->verifySign == NULL || method->checkPrivateKey == NULL; if (valid) { return false; } return true; } int32_t HITLS_CERT_RegisterMgrMethod(HITLS_CERT_MgrMethod *method) { /* check the callbacks that must be set */ if (IsMethodValid(method) == false) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID16108, "input NULL"); } if (memcpy_s(&g_certMgrMethod, sizeof(HITLS_CERT_MgrMethod), method, sizeof(HITLS_CERT_MgrMethod)) != EOK) { return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } void HITLS_CERT_DeinitMgrMethod(void) { HITLS_CERT_MgrMethod mgr = {0}; (void)memcpy_s(&g_certMgrMethod, sizeof(HITLS_CERT_MgrMethod), &mgr, sizeof(HITLS_CERT_MgrMethod)); } HITLS_CERT_MgrMethod *SAL_CERT_GetMgrMethod(void) { return &g_certMgrMethod; } HITLS_CERT_MgrMethod *HITLS_CERT_GetMgrMethod(void) { return SAL_CERT_GetMgrMethod(); } #endif /* HITLS_TLS_FEATURE_PROVIDER */ int32_t CheckCertCallBackRetVal(const char *logStr, int32_t callBackRet, uint32_t bingLogId, uint32_t hitlsRet) { if (callBackRet != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(bingLogId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "%s error: callback ret = 0x%x.", logStr, callBackRet, 0, 0); BSL_ERR_PUSH_ERROR((int32_t)hitlsRet); return (int32_t)hitlsRet; } return HITLS_SUCCESS; } HITLS_CERT_Store *SAL_CERT_StoreNew(const CERT_MgrCtx *mgrCtx) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_X509_ProviderStoreCtxNew(LIBCTX_FROM_CERT_MGR_CTX(mgrCtx), ATTRIBUTE_FROM_CERT_MGR_CTX(mgrCtx)); #else return mgrCtx->method.certStoreNew(); #endif } HITLS_CERT_Store *SAL_CERT_StoreDup(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store) { #ifdef HITLS_TLS_FEATURE_PROVIDER (void)mgrCtx; return HITLS_X509_Adapt_StoreDup(store); #else return mgrCtx->method.certStoreDup(store); #endif } void SAL_CERT_StoreFree(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store) { #ifdef HITLS_TLS_FEATURE_PROVIDER (void)mgrCtx; return HITLS_X509_StoreCtxFree(store); #else mgrCtx->method.certStoreFree(store); #endif } int32_t SAL_CERT_BuildChain(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_X509 *cert, HITLS_CERT_X509 **certList, uint32_t *num) { int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_BuildCertChain(config, store, cert, certList, num); #else ret = config->certMgrCtx->method.buildCertChain(config, store, cert, certList, num); #endif return CheckCertCallBackRetVal("cert store build chain by cert", ret, BINLOG_ID16083, HITLS_CERT_ERR_BUILD_CHAIN); } int32_t SAL_CERT_VerifyChain(HITLS_Ctx *ctx, HITLS_CERT_Store *store, HITLS_CERT_X509 **certList, uint32_t num) { int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_VerifyCertChain(ctx, store, certList, num); #else ret = ctx->config.tlsConfig.certMgrCtx->method.verifyCertChain(ctx, store, certList, num); #endif return CheckCertCallBackRetVal("cert store verify chain", ret, BINLOG_ID16084, HITLS_CERT_ERR_VERIFY_CERT_CHAIN); } int32_t SAL_CERT_X509Encode(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, uint8_t *buf, uint32_t len, uint32_t *usedLen) { int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_CertEncode(ctx, cert, buf, len, usedLen); #else ret = ctx->config.tlsConfig.certMgrCtx->method.certEncode(ctx, cert, buf, len, usedLen); #endif return CheckCertCallBackRetVal("encode cert", ret, BINLOG_ID16086, HITLS_CERT_ERR_ENCODE_CERT); } HITLS_CERT_Chain *SAL_CERT_X509ParseBundleFile(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { (void)config; return HITLS_X509_Adapt_BundleCertParse(libCtx, attrName, buf, len, type, SAL_CERT_GetParseFormatStr(format)); } HITLS_CERT_X509 *SAL_CERT_X509Parse(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { #ifdef HITLS_TLS_FEATURE_PROVIDER (void)config; return HITLS_CERT_ProviderCertParse(libCtx, attrName, buf, len, type, SAL_CERT_GetParseFormatStr(format)); #else (void)libCtx; (void)attrName; return config->certMgrCtx->method.certParse(config, buf, len, type, format); #endif } HITLS_CERT_X509 *SAL_CERT_X509Dup(const CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert) { #ifdef HITLS_TLS_FEATURE_PROVIDER (void)mgrCtx; return (HITLS_CERT_X509 *)HITLS_X509_CertDup(cert); #else return mgrCtx->method.certDup(cert); #endif } void SAL_CERT_X509Free(HITLS_CERT_X509 *cert) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_X509_CertFree(cert); #else if (cert == NULL) { return; } g_certMgrMethod.certFree(cert); #endif } HITLS_CERT_X509 *SAL_CERT_X509Ref(const CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert) { #ifdef HITLS_TLS_FEATURE_PROVIDER (void)mgrCtx; return HITLS_X509_Adapt_CertRef(cert); #else if (mgrCtx->method.certRef == NULL) { return NULL; } return mgrCtx->method.certRef(cert); #endif } typedef struct { const char *name; HITLS_ParseFormat format; } ParseFormatMap; static const ParseFormatMap g_parseFormatMap[] = { {"PEM", TLS_PARSE_FORMAT_PEM}, {"ASN1", TLS_PARSE_FORMAT_ASN1}, {"PFX_COM", TLS_PARSE_FORMAT_PFX_COM}, {"PKCS12", TLS_PARSE_FORMAT_PKCS12} }; const char *SAL_CERT_GetParseFormatStr(HITLS_ParseFormat format) { for (size_t i = 0; i < sizeof(g_parseFormatMap) / sizeof(g_parseFormatMap[0]); i++) { if (g_parseFormatMap[i].format == format) { return g_parseFormatMap[i].name; } } return NULL; } #ifndef HITLS_TLS_FEATURE_PROVIDER static HITLS_ParseFormat GetTlsParseFormat(const char *format) { if (format == NULL) { return TLS_PARSE_FORMAT_BUTT; } for (size_t i = 0; i < sizeof(g_parseFormatMap) / sizeof(g_parseFormatMap[0]); i++) { if (BSL_SAL_StrcaseCmp(format, g_parseFormatMap[i].name) == 0) { return g_parseFormatMap[i].format; } } return TLS_PARSE_FORMAT_BUTT; } #endif HITLS_CERT_Key *SAL_CERT_KeyParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format, const char *encodeType) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_X509_Adapt_ProviderKeyParse(config, buf, len, type, format, encodeType); #else (void)encodeType; return config->certMgrCtx->method.keyParse(config, buf, len, type, GetTlsParseFormat(format)); #endif } HITLS_CERT_Key *SAL_CERT_KeyDup(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Key *key) { #ifdef HITLS_TLS_FEATURE_PROVIDER (void)mgrCtx; return (HITLS_CERT_Key *)CRYPT_EAL_PkeyDupCtx(key); #else return mgrCtx->method.keyDup(key); #endif } void SAL_CERT_KeyFree(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Key *key) { #ifdef HITLS_TLS_FEATURE_PROVIDER (void)mgrCtx; CRYPT_EAL_PkeyFreeCtx(key); #else if (key == NULL) { return; } mgrCtx->method.keyFree(key); #endif } /* change the error code when modifying the ctrl command */ static const struct { HITLS_CERT_CtrlCmd cmd; uint32_t err; } g_tlsCertCtrlErrorCode[] = { { CERT_STORE_CTRL_SET_VERIFY_DEPTH, HITLS_CERT_STORE_CTRL_ERR_SET_VERIFY_DEPTH }, { CERT_STORE_CTRL_ADD_CERT_LIST, HITLS_CERT_STORE_CTRL_ERR_ADD_CERT_LIST }, { CERT_STORE_CTRL_ADD_CRL_LIST, HITLS_CERT_STORE_CTRL_ERR_ADD_CRL_LIST }, { CERT_STORE_CTRL_CLEAR_CRL_LIST, HITLS_CERT_STORE_CTRL_ERR_CLEAR_CRL_LIST }, { CERT_STORE_CTRL_GET_VERIFY_DEPTH, HITLS_CERT_STORE_CTRL_ERR_GET_VERIFY_DEPTH }, { CERT_CTRL_GET_ENCODE_LEN, HITLS_CERT_CTRL_ERR_GET_ENCODE_LEN }, { CERT_CTRL_GET_PUB_KEY, HITLS_CERT_CTRL_ERR_GET_PUB_KEY }, { CERT_CTRL_GET_SIGN_ALGO, HITLS_CERT_CTRL_ERR_GET_SIGN_ALGO }, { CERT_CTRL_GET_ENCODE_SUBJECT_DN, HITLS_CERT_CTRL_ERR_GET_SUBJECT_DN }, { CERT_CTRL_IS_SELF_SIGNED, HITLS_CERT_CTRL_ERR_IS_SELF_SIGNED }, { CERT_KEY_CTRL_GET_SIGN_LEN, HITLS_CERT_KEY_CTRL_ERR_GET_SIGN_LEN }, { CERT_KEY_CTRL_GET_TYPE, HITLS_CERT_KEY_CTRL_ERR_GET_TYPE }, { CERT_KEY_CTRL_GET_CURVE_NAME, HITLS_CERT_KEY_CTRL_ERR_GET_CURVE_NAME }, { CERT_KEY_CTRL_GET_POINT_FORMAT, HITLS_CERT_KEY_CTRL_ERR_GET_POINT_FORMAT }, { CERT_KEY_CTRL_GET_SECBITS, HITLS_CERT_KEY_CTRL_ERR_GET_SECBITS }, { CERT_KEY_CTRL_IS_KEYENC_USAGE, HITLS_CERT_KEY_CTRL_ERR_IS_ENC_USAGE }, { CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE, HITLS_CERT_KEY_CTRL_ERR_IS_DIGITAL_SIGN_USAGE }, { CERT_KEY_CTRL_IS_KEY_CERT_SIGN_USAGE, HITLS_CERT_KEY_CTRL_ERR_IS_KEY_CERT_SIGN_USAGE }, { CERT_KEY_CTRL_IS_KEY_AGREEMENT_USAGE, HITLS_CERT_KEY_CTRL_ERR_IS_KEY_AGREEMENT_USAGE }, { CERT_KEY_CTRL_GET_PARAM_ID, HITLS_CERT_KEY_CTRL_ERR_GET_PARAM_ID }, { CERT_KEY_CTRL_IS_DATA_ENC_USAGE, HITLS_CERT_KEY_CTRL_ERR_IS_DATA_ENC_USAGE }, { CERT_KEY_CTRL_IS_NON_REPUDIATION_USAGE, HITLS_CERT_KEY_CTRL_ERR_IS_NON_REPUDIATION_USAGE }, { CERT_STORE_CTRL_GET_VERIFY_FLAGS, HITLS_CERT_STORE_CTRL_ERR_GET_VERIFY_FLAGS }, { CERT_STORE_CTRL_SET_VERIFY_FLAGS, HITLS_CERT_STORE_CTRL_ERR_SET_VERIFY_FLAGS }, }; static uint32_t GetTlsCertCtrlErrorCode(HITLS_CERT_CtrlCmd cmd) { for (size_t i = 0; i < sizeof(g_tlsCertCtrlErrorCode) / sizeof(g_tlsCertCtrlErrorCode[0]); i++) { if (g_tlsCertCtrlErrorCode[i].cmd == cmd) { return g_tlsCertCtrlErrorCode[i].err; } } return HITLS_CERT_CTRL_ERR_INVALID_CMD; } int32_t SAL_CERT_StoreCtrl(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_CtrlCmd cmd, void *in, void *out) { int32_t ret; if (cmd > CERT_CTRL_BUTT - 1) { BSL_ERR_PUSH_ERROR(HITLS_CERT_CTRL_ERR_INVALID_CMD); return HITLS_CERT_CTRL_ERR_INVALID_CMD; } #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_StoreCtrl(config, store, cmd, in, out); #else ret = config->certMgrCtx->method.certStoreCtrl(config, store, cmd, in, out); #endif return CheckCertCallBackRetVal("cert store ctrl", ret, BINLOG_ID16094, GetTlsCertCtrlErrorCode(cmd)); } int32_t SAL_CERT_X509Ctrl(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_CtrlCmd cmd, void *in, void *out) { if (cert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16279, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } if (cmd > CERT_CTRL_BUTT - 1) { BSL_ERR_PUSH_ERROR(HITLS_CERT_CTRL_ERR_INVALID_CMD); return HITLS_CERT_CTRL_ERR_INVALID_CMD; } int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_CertCtrl(config, cert, cmd, in, out); #else ret = config->certMgrCtx->method.certCtrl(config, cert, cmd, in, out); #endif return CheckCertCallBackRetVal("cert ctrl", ret, BINLOG_ID16096, GetTlsCertCtrlErrorCode(cmd)); } int32_t SAL_CERT_KeyCtrl(HITLS_Config *config, HITLS_CERT_Key *key, HITLS_CERT_CtrlCmd cmd, void *in, void *out) { if (key == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16280, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } if (cmd > CERT_CTRL_BUTT - 1) { BSL_ERR_PUSH_ERROR(HITLS_CERT_CTRL_ERR_INVALID_CMD); return HITLS_CERT_CTRL_ERR_INVALID_CMD; } int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_KeyCtrl(config, key, cmd, in, out); #else ret = config->certMgrCtx->method.keyCtrl(config, key, cmd, in, out); #endif return CheckCertCallBackRetVal("key ctrl", ret, BINLOG_ID16098, GetTlsCertCtrlErrorCode(cmd)); } int32_t SAL_CERT_CreateSign(HITLS_Ctx *ctx, HITLS_CERT_Key *key, CERT_SignParam *signParam) { if (key == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16281, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_CreateSign(ctx, key, signParam->signAlgo, signParam->hashAlgo, signParam->data, signParam->dataLen, signParam->sign, &signParam->signLen); #else ret = ctx->config.tlsConfig.certMgrCtx->method.createSign(ctx, key, signParam->signAlgo, signParam->hashAlgo, signParam->data, signParam->dataLen, signParam->sign, &signParam->signLen); #endif return CheckCertCallBackRetVal("create signature", ret, BINLOG_ID16103, HITLS_CERT_ERR_CREATE_SIGN); } int32_t SAL_CERT_VerifySign(HITLS_Ctx *ctx, HITLS_CERT_Key *key, CERT_SignParam *signParam) { int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_VerifySign(ctx, key, signParam->signAlgo, signParam->hashAlgo, signParam->data, signParam->dataLen, signParam->sign, signParam->signLen); #else ret = ctx->config.tlsConfig.certMgrCtx->method.verifySign(ctx, key, signParam->signAlgo, signParam->hashAlgo, signParam->data, signParam->dataLen, signParam->sign, signParam->signLen); #endif return CheckCertCallBackRetVal("verify signature", ret, BINLOG_ID16101, HITLS_CERT_ERR_VERIFY_SIGN); } #if defined(HITLS_TLS_SUITE_KX_RSA) || defined(HITLS_TLS_PROTO_TLCP11) int32_t SAL_CERT_KeyEncrypt(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_Encrypt(ctx, key, in, inLen, out, outLen); #else if (ctx->config.tlsConfig.certMgrCtx->method.encrypt == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID15333, "unregistered encrypt"); } ret = ctx->config.tlsConfig.certMgrCtx->method.encrypt(ctx, key, in, inLen, out, outLen); #endif return CheckCertCallBackRetVal("pubkey encrypt", ret, BINLOG_ID15059, HITLS_CERT_ERR_ENCRYPT); } int32_t SAL_CERT_KeyDecrypt(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_X509_Adapt_Decrypt(ctx, key, in, inLen, out, outLen); #else if (ctx->config.tlsConfig.certMgrCtx->method.decrypt == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID15334, "unregistered decrypt"); } return ctx->config.tlsConfig.certMgrCtx->method.decrypt(ctx, key, in, inLen, out, outLen); #endif } #endif /* HITLS_TLS_SUITE_KX_RSA || HITLS_TLS_PROTO_TLCP11 */ int32_t SAL_CERT_CheckPrivateKey(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_Key *key) { int32_t ret; #ifdef HITLS_TLS_FEATURE_PROVIDER ret = HITLS_X509_Adapt_CheckPrivateKey(config, cert, key); #else ret = config->certMgrCtx->method.checkPrivateKey(config, cert, key); #endif return CheckCertCallBackRetVal( "check cert and private key", ret, BINLOG_ID15538, HITLS_CERT_ERR_CHECK_CERT_AND_KEY); } HITLS_CERT_CRLList *SAL_CERT_CrlParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { return HITLS_X509_Adapt_CrlParse(config, buf, len, type, format); } void SAL_CERT_CrlFree(HITLS_CERT_CRLList *crlList) { HITLS_X509_Adapt_CrlFree(crlList); }
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/cert_adapt/cert_method.c
C
unknown
17,133
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include "securec.h" #include "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_cert_reg.h" #include "tls_config.h" #include "cert_method.h" #include "cert_mgr_ctx.h" bool SAL_CERT_MgrIsEnable(void) { #ifdef HITLS_TLS_FEATURE_PROVIDER return true; #else HITLS_CERT_MgrMethod *method = SAL_CERT_GetMgrMethod(); return (method->certStoreNew != NULL); #endif } CERT_MgrCtx *SAL_CERT_MgrCtxNew(void) { return SAL_CERT_MgrCtxProviderNew(NULL, NULL); } CERT_MgrCtx *SAL_CERT_MgrCtxProviderNew(HITLS_Lib_Ctx *libCtx, const char *attrName) { CERT_MgrCtx *newCtx = BSL_SAL_Calloc(1, sizeof(CERT_MgrCtx)); if (newCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16085, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "new cert manager context error: out of memory.", 0, 0, 0, 0); return NULL; } newCtx->currentCertKeyType = TLS_CERT_KEY_TYPE_UNKNOWN; newCtx->certPairs = BSL_HASH_Create(CERT_DEFAULT_HASH_BKT_SIZE, NULL, NULL, NULL, NULL); if (newCtx->certPairs == NULL) { BSL_SAL_FREE(newCtx); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17338, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "new cert manager context error: new certPairs failed.", 0, 0, 0, 0); return NULL; } #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_MgrMethod *method = SAL_CERT_GetMgrMethod(); (void)memcpy_s(&newCtx->method, sizeof(HITLS_CERT_MgrMethod), method, sizeof(HITLS_CERT_MgrMethod)); #endif newCtx->certStore = SAL_CERT_StoreNew(newCtx); if (newCtx->certStore == NULL) { BSL_HASH_Destory(newCtx->certPairs); BSL_SAL_FREE(newCtx); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15016, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "new cert manager context error: new store failed.", 0, 0, 0, 0); return NULL; } newCtx->libCtx = libCtx; newCtx->attrName = attrName; return newCtx; } int32_t StoreDup(CERT_MgrCtx *destMgrCtx, CERT_MgrCtx *srcMgrCtx) { if (srcMgrCtx->certStore != NULL) { destMgrCtx->certStore = SAL_CERT_StoreDup(srcMgrCtx, srcMgrCtx->certStore); if (destMgrCtx->certStore == NULL) { /* releasing resources at the call point */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_STORE_DUP, BINLOG_ID16092, "StoreDup fail"); } } if (srcMgrCtx->chainStore != NULL) { destMgrCtx->chainStore = SAL_CERT_StoreDup(srcMgrCtx, srcMgrCtx->chainStore); if (destMgrCtx->chainStore == NULL) { /* releasing resources at the call point */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_STORE_DUP, BINLOG_ID16093, "StoreDup fail"); } } if (srcMgrCtx->verifyStore != NULL) { destMgrCtx->verifyStore = SAL_CERT_StoreDup(srcMgrCtx, srcMgrCtx->verifyStore); if (destMgrCtx->verifyStore == NULL) { /* releasing resources at the call point */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_STORE_DUP, BINLOG_ID16095, "StoreDup fail"); } } return HITLS_SUCCESS; } CERT_MgrCtx *SAL_CERT_MgrCtxDup(CERT_MgrCtx *mgrCtx) { int32_t ret; if (mgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16282, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "mgrCtx null", 0, 0, 0, 0); return NULL; } CERT_MgrCtx *newCtx = BSL_SAL_Calloc(1, sizeof(CERT_MgrCtx)); if (newCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16097, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "dup cert manager context error: out of memory.", 0, 0, 0, 0); return NULL; } #ifndef HITLS_TLS_FEATURE_PROVIDER (void)memcpy_s(&newCtx->method, sizeof(HITLS_CERT_MgrMethod), &mgrCtx->method, sizeof(HITLS_CERT_MgrMethod)); #endif ret = SAL_CERT_HashDup(newCtx, mgrCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16283, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SAL_CERT_HashDup fail, ret %d", ret, 0, 0, 0); SAL_CERT_MgrCtxFree(newCtx); return NULL; } if (mgrCtx->extraChain != NULL) { newCtx->extraChain = SAL_CERT_ChainDup(mgrCtx, mgrCtx->extraChain); if (newCtx->extraChain == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16284, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ChainDup fail", 0, 0, 0, 0); SAL_CERT_MgrCtxFree(newCtx); return NULL; } } ret = StoreDup(newCtx, mgrCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16285, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "StoreDup fail, ret %d", ret, 0, 0, 0); SAL_CERT_MgrCtxFree(newCtx); return NULL; } newCtx->currentCertKeyType = mgrCtx->currentCertKeyType; newCtx->defaultPasswdCb = mgrCtx->defaultPasswdCb; newCtx->defaultPasswdCbUserData = mgrCtx->defaultPasswdCbUserData; newCtx->verifyCb = mgrCtx->verifyCb; newCtx->libCtx = LIBCTX_FROM_CERT_MGR_CTX(mgrCtx); newCtx->attrName = ATTRIBUTE_FROM_CERT_MGR_CTX(mgrCtx); #ifdef HITLS_TLS_FEATURE_CERT_CB newCtx->certCb = mgrCtx->certCb; newCtx->certCbArg = mgrCtx->certCbArg; #endif /* HITLS_TLS_FEATURE_CERT_CB */ return newCtx; } void SAL_CERT_MgrCtxFree(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return; } SAL_CERT_ClearCertAndKey(mgrCtx); SAL_CERT_ChainFree(mgrCtx->extraChain); mgrCtx->extraChain = NULL; SAL_CERT_StoreFree(mgrCtx, mgrCtx->verifyStore); mgrCtx->verifyStore = NULL; SAL_CERT_StoreFree(mgrCtx, mgrCtx->chainStore); mgrCtx->chainStore = NULL; SAL_CERT_StoreFree(mgrCtx, mgrCtx->certStore); mgrCtx->certStore = NULL; BSL_HASH_Destory(mgrCtx->certPairs); mgrCtx->certPairs = NULL; BSL_SAL_FREE(mgrCtx); return; }
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/cert_adapt/cert_mgr_create.c
C
unknown
6,550
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include "securec.h" #include "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 "cert_method.h" #include "cert.h" #include "cert_mgr_ctx.h" int32_t SAL_CERT_SetCertStore(CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store) { if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } SAL_CERT_StoreFree(mgrCtx, mgrCtx->certStore); mgrCtx->certStore = store; return HITLS_SUCCESS; } HITLS_CERT_Store *SAL_CERT_GetCertStore(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return NULL; } return mgrCtx->certStore; } int32_t SAL_CERT_SetChainStore(CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store) { if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } SAL_CERT_StoreFree(mgrCtx, mgrCtx->chainStore); mgrCtx->chainStore = store; return HITLS_SUCCESS; } HITLS_CERT_Store *SAL_CERT_GetChainStore(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return NULL; } return mgrCtx->chainStore; } int32_t SAL_CERT_SetVerifyStore(CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store) { if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } SAL_CERT_StoreFree(mgrCtx, mgrCtx->verifyStore); mgrCtx->verifyStore = store; return HITLS_SUCCESS; } HITLS_CERT_Store *SAL_CERT_GetVerifyStore(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return NULL; } return mgrCtx->verifyStore; } static int32_t GetOrInsertCertPair(CERT_MgrCtx *mgrCtx, HITLS_CERT_KeyType keyType, CERT_Pair **certPair) { CERT_Pair *newCertPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)keyType, (uintptr_t *)&newCertPair); if (ret != HITLS_SUCCESS || newCertPair == NULL) { newCertPair = BSL_SAL_Calloc(1u, sizeof(CERT_Pair)); if (newCertPair == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16102, "certPair calloc fail"); } ret = BSL_HASH_Insert(mgrCtx->certPairs, keyType, 0, (uintptr_t)newCertPair, sizeof(CERT_Pair)); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(newCertPair); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17339, "insert fail"); } } *certPair = newCertPair; return HITLS_SUCCESS; } int32_t SAL_CERT_SetCurrentCert(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isTlcpEncCert) { (void)isTlcpEncCert; if (cert == NULL || config == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_UNREGISTERED_CALLBACK); return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16286, "unregistered callback"); } HITLS_CERT_Key *pubkey = NULL; int32_t ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16099, "GET PUB KEY fail"); } uint32_t keyType = TLS_CERT_KEY_TYPE_UNKNOWN; ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_TYPE, NULL, (void *)&keyType); SAL_CERT_KeyFree(mgrCtx, pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16100, "GET KEY TYPE fail"); } CERT_Pair *certPair = NULL; ret = GetOrInsertCertPair(mgrCtx, keyType, &certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { return HITLS_MEMALLOC_FAIL; } HITLS_CERT_Key **privateKey = NULL; HITLS_CERT_X509 **certPairCert = NULL; #ifdef HITLS_TLS_PROTO_TLCP11 if (isTlcpEncCert) { privateKey = &certPair->encPrivateKey; certPairCert = &certPair->encCert; } else #endif { privateKey = &certPair->privateKey; certPairCert = &certPair->cert; } if (*privateKey != NULL) { ret = SAL_CERT_CheckPrivateKey(config, cert, *privateKey); if (ret != HITLS_SUCCESS) { /* If the certificate does not match the private key, release the private key. */ SAL_CERT_KeyFree(mgrCtx, *privateKey); *privateKey = NULL; } } SAL_CERT_X509Free(*certPairCert); *certPairCert = cert; mgrCtx->currentCertKeyType = keyType; return HITLS_SUCCESS; } HITLS_CERT_X509 *SAL_CERT_GetCurrentCert(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16287, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "mgrCtx null", 0, 0, 0, 0); return NULL; } uint32_t keyType = mgrCtx->currentCertKeyType; CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)keyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16288, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "idx err", 0, 0, 0, 0); return NULL; } return certPair->cert; } HITLS_CERT_X509 *SAL_CERT_GetCert(CERT_MgrCtx *mgrCtx, HITLS_CERT_KeyType keyType) { if (mgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16289, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "mgrCtx null", 0, 0, 0, 0); return NULL; } CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)keyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16290, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "idx err", 0, 0, 0, 0); return NULL; } return certPair->cert; } int32_t SAL_CERT_SetCurrentPrivateKey(HITLS_Config *config, HITLS_CERT_Key *key, bool isTlcpEncCertPriKey) { (void)isTlcpEncCertPriKey; if (key == NULL || config == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_UNREGISTERED_CALLBACK); return HITLS_UNREGISTERED_CALLBACK; } uint32_t keyType = TLS_CERT_KEY_TYPE_UNKNOWN; int32_t ret = SAL_CERT_KeyCtrl(config, key, CERT_KEY_CTRL_GET_TYPE, NULL, (void *)&keyType); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16104, "get key type fail"); } CERT_Pair *certPair = NULL; ret = GetOrInsertCertPair(mgrCtx, keyType, &certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { return HITLS_MEMALLOC_FAIL; } HITLS_CERT_Key **certPairPrivateKey = NULL; HITLS_CERT_X509 **cert = NULL; #ifdef HITLS_TLS_PROTO_TLCP11 if (isTlcpEncCertPriKey) { certPairPrivateKey = &certPair->encPrivateKey; cert = &certPair->encCert; } else #endif { certPairPrivateKey = &certPair->privateKey; cert = &certPair->cert; } if (*cert != NULL) { ret = SAL_CERT_CheckPrivateKey(config, *cert, key); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16107, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set private key error: cert and key mismatch, key type = %u.", keyType, 0, 0, 0); /* The certificate does not match the private key. */ return ret; } } SAL_CERT_KeyFree(mgrCtx, *certPairPrivateKey); *certPairPrivateKey = key; mgrCtx->currentCertKeyType = keyType; return HITLS_SUCCESS; } HITLS_CERT_Key *SAL_CERT_GetCurrentPrivateKey(CERT_MgrCtx *mgrCtx, bool isTlcpEncCert) { (void)isTlcpEncCert; if (mgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16291, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "mgrCtx null", 0, 0, 0, 0); return NULL; } uint32_t keyType = mgrCtx->currentCertKeyType; CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)keyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16292, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certPair null", 0, 0, 0, 0); return NULL; } #ifdef HITLS_TLS_PROTO_TLCP11 if (isTlcpEncCert) { return certPair->encPrivateKey; } #endif return certPair->privateKey; } HITLS_CERT_Key *SAL_CERT_GetPrivateKey(CERT_MgrCtx *mgrCtx, HITLS_CERT_KeyType keyType) { if (mgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16293, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "mgrCtx null", 0, 0, 0, 0); return NULL; } CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)keyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16294, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certPair null", 0, 0, 0, 0); return NULL; } return certPair->privateKey; } int32_t SAL_CERT_AddChainCert(CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert) { if (mgrCtx == NULL || cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID16392, "null input"); } uint32_t keyType = mgrCtx->currentCertKeyType; if (keyType == TLS_CERT_KEY_TYPE_UNKNOWN) { BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_ADD_CHAIN_CERT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_ADD_CHAIN_CERT, BINLOG_ID16390, "keyType unknown"); } CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)keyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { /* the certificate has not been loaded yet */ BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_ADD_CHAIN_CERT); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_ADD_CHAIN_CERT, BINLOG_ID16391, "certPair null"); } HITLS_CERT_Chain *newChain = NULL; HITLS_CERT_Chain *chain = certPair->chain; if (chain == NULL) { newChain = SAL_CERT_ChainNew(); if (newChain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16295, "ChainNew fail"); } chain = newChain; } ret = SAL_CERT_ChainAppend(chain, cert); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(newChain); return ret; } certPair->chain = chain; return HITLS_SUCCESS; } HITLS_CERT_Chain *SAL_CERT_GetCurrentChainCerts(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16296, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "mgrCtx null", 0, 0, 0, 0); return NULL; } CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)mgrCtx->currentCertKeyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16297, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certPair null", 0, 0, 0, 0); return NULL; } return certPair->chain; } void SAL_CERT_ClearCurrentChainCerts(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return; } CERT_Pair *certPair = NULL; int32_t ret = BSL_HASH_At(mgrCtx->certPairs, (uintptr_t)mgrCtx->currentCertKeyType, (uintptr_t *)&certPair); if (ret != HITLS_SUCCESS || certPair == NULL || certPair->chain == NULL) { return; } SAL_CERT_ChainFree(certPair->chain); certPair->chain = NULL; return; } void SAL_CERT_ClearCertAndKey(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return; } BSL_HASH_Hash *certPairs = mgrCtx->certPairs; for (BSL_HASH_Iterator it = BSL_HASH_IterBegin(certPairs); it != BSL_HASH_IterEnd(certPairs);) { uint32_t keyType = (uint32_t)BSL_HASH_HashIterKey(certPairs, it); CERT_Pair *certPair = (CERT_Pair *)BSL_HASH_IterValue(certPairs, it); SAL_CERT_PairClear(mgrCtx, certPair); BSL_SAL_FREE(certPair); it = BSL_HASH_Erase(certPairs, keyType); } mgrCtx->currentCertKeyType = TLS_CERT_KEY_TYPE_UNKNOWN; return; } int32_t SAL_CERT_AddExtraChainCert(CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert) { if (mgrCtx == NULL || cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } HITLS_CERT_Chain *newChain = NULL; HITLS_CERT_Chain *chain = mgrCtx->extraChain; if (chain == NULL) { newChain = SAL_CERT_ChainNew(); if (newChain == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID16298, "ChainNew fail"); } chain = newChain; } int32_t ret = SAL_CERT_ChainAppend(chain, cert); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(newChain); return ret; } mgrCtx->extraChain = chain; return HITLS_SUCCESS; } HITLS_CERT_Chain *SAL_CERT_GetExtraChainCerts(CERT_MgrCtx *mgrCtx, bool isExtraChainCertsOnly) { if (mgrCtx == NULL) { return NULL; } if (mgrCtx->extraChain == NULL && !isExtraChainCertsOnly) { return SAL_CERT_GetCurrentChainCerts(mgrCtx); } return mgrCtx->extraChain; } void SAL_CERT_ClearExtraChainCerts(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return; } HITLS_CERT_Chain *chain = mgrCtx->extraChain; if (chain == NULL) { return; } SAL_CERT_ChainFree(chain); mgrCtx->extraChain = NULL; return; } int32_t SAL_CERT_CtrlVerifyParams(HITLS_Config *config, HITLS_CERT_Store *store, uint32_t cmd, void *in, void *out) { CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } HITLS_CERT_Store *tempStore = store; if (tempStore == NULL) { tempStore = (mgrCtx->verifyStore != NULL) ? mgrCtx->verifyStore : mgrCtx->certStore; if (tempStore == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_NULL_INPUT, BINLOG_ID15327, "store is null"); } } int32_t ret = SAL_CERT_StoreCtrl(config, tempStore, cmd, in, out); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID15326, "SAL_CERT_StoreCtrl fail"); } return HITLS_SUCCESS; } int32_t SAL_CERT_SetDefaultPasswordCb(CERT_MgrCtx *mgrCtx, HITLS_PasswordCb cb) { if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } mgrCtx->defaultPasswdCb = cb; return HITLS_SUCCESS; } HITLS_PasswordCb SAL_CERT_GetDefaultPasswordCb(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return NULL; } return mgrCtx->defaultPasswdCb; } int32_t SAL_CERT_SetDefaultPasswordCbUserdata(CERT_MgrCtx *mgrCtx, void *userdata) { if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } mgrCtx->defaultPasswdCbUserData = userdata; return HITLS_SUCCESS; } void *SAL_CERT_GetDefaultPasswordCbUserdata(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return NULL; } return mgrCtx->defaultPasswdCbUserData; } int32_t SAL_CERT_SetVerifyCb(CERT_MgrCtx *mgrCtx, HITLS_VerifyCb cb) { if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } mgrCtx->verifyCb = cb; return HITLS_SUCCESS; } HITLS_VerifyCb SAL_CERT_GetVerifyCb(CERT_MgrCtx *mgrCtx) { if (mgrCtx == NULL) { return NULL; } return mgrCtx->verifyCb; } #ifdef HITLS_TLS_FEATURE_CERT_CB int32_t SAL_CERT_SetCertCb(CERT_MgrCtx *mgrCtx, HITLS_CertCb certCb, void *arg) { if (mgrCtx == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } mgrCtx->certCb = certCb; mgrCtx->certCbArg = arg; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_CERT_CB */
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/cert_adapt/cert_mgr_ctrl.c
C
unknown
16,552
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CERT_MGR_CTX_H #define CERT_MGR_CTX_H #include <stdint.h> #include "hitls_crypt_type.h" #include "hitls_cert_reg.h" #include "cert.h" #include "bsl_hash.h" #ifdef __cplusplus extern "C" { #endif #define CERT_DEFAULT_HASH_BKT_SIZE 64u struct CertPairInner { HITLS_CERT_X509 *cert; /* device certificate */ #ifdef HITLS_TLS_PROTO_TLCP11 /* encrypted device cert. Currently this field is used only when the peer-end encrypted certificate is stored. */ HITLS_CERT_X509 *encCert; HITLS_CERT_Key *encPrivateKey; #endif HITLS_CERT_Key *privateKey; /* private key corresponding to the certificate */ HITLS_CERT_Chain *chain; /* certificate chain */ }; struct CertMgrCtxInner { uint32_t currentCertKeyType; /* keyType to the certificate in use. */ /* Indicates the certificate resources on the link. Only one certificate of a type can be loaded. */ BSL_HASH_Hash *certPairs; /* cert hash table. key keyType, value CERT_Pair */ HITLS_CERT_Chain *extraChain; HITLS_CERT_Store *verifyStore; /* Verifies the store, which is used to verify the certificate chain. */ HITLS_CERT_Store *chainStore; /* Certificate chain store, used to assemble the certificate chain */ HITLS_CERT_Store *certStore; /* Default CA store */ #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_MgrMethod method; /* callback function */ #endif HITLS_PasswordCb defaultPasswdCb; /* Default password callback, used in loading certificate. */ void *defaultPasswdCbUserData; /* Set the userData used by the default password callback. */ HITLS_VerifyCb verifyCb; /* Certificate verification callback function */ #ifdef HITLS_TLS_FEATURE_CERT_CB HITLS_CertCb certCb; /* Certificate callback function */ void *certCbArg; /* Argument for the certificate callback function */ #endif /* HITLS_TLS_FEATURE_CERT_CB */ HITLS_Lib_Ctx *libCtx; /* library context */ const char *attrName; /* attrName */ }; CERT_Type CertKeyType2CertType(HITLS_CERT_KeyType keyType); int32_t CheckCurveName(HITLS_Config *config, const uint16_t *curveList, uint32_t curveNum, HITLS_CERT_Key *pubkey); int32_t CheckPointFormat(HITLS_Config *config, const uint8_t *ecPointFormatList, uint32_t listSize, HITLS_CERT_Key *pubkey); /* These functions can be stored in a separate header file. */ HITLS_CERT_Chain *SAL_CERT_ChainNew(void); int32_t SAL_CERT_ChainAppend(HITLS_CERT_Chain *chain, HITLS_CERT_X509 *cert); HITLS_CERT_Chain *SAL_CERT_ChainDup(CERT_MgrCtx *mgrCtx, HITLS_CERT_Chain *chain); #define LIBCTX_FROM_CERT_MGR_CTX(mgrCtx) ((mgrCtx == NULL) ? NULL : (mgrCtx)->libCtx) #define ATTRIBUTE_FROM_CERT_MGR_CTX(mgrCtx) ((mgrCtx == NULL) ? NULL : (mgrCtx)->attrName) #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/cert_adapt/cert_mgr_ctx.h
C
unknown
3,486
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_cert_type.h" #include "cert_method.h" #include "cert_mgr.h" #include "cert_mgr_ctx.h" HITLS_CERT_X509 *SAL_CERT_PairGetX509(CERT_Pair *certPair) { if (certPair == NULL) { return NULL; } return certPair->cert; } #ifdef HITLS_TLS_PROTO_TLCP11 HITLS_CERT_X509 *SAL_CERT_GetTlcpEncCert(CERT_Pair *certPair) { if (certPair == NULL) { return NULL; } return certPair->encCert; } #endif #if defined(HITLS_TLS_CONNECTION_INFO_NEGOTIATION) HITLS_CERT_Chain *SAL_CERT_PairGetChain(CERT_Pair *certPair) { if (certPair == NULL) { return NULL; } return certPair->chain; } #endif /* HITLS_TLS_CONNECTION_INFO_NEGOTIATION */ #ifdef HITLS_TLS_PROTO_TLCP11 static int32_t TlcpCertPairDup(CERT_MgrCtx *mgrCtx, CERT_Pair *srcCertPair, CERT_Pair *destCertPair) { if (srcCertPair->encCert != NULL) { destCertPair->encCert = SAL_CERT_X509Dup(mgrCtx, srcCertPair->encCert); if (destCertPair->encCert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17341, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "enc X509Dup fail", 0, 0, 0, 0); return HITLS_CERT_ERR_X509_DUP; } } if (srcCertPair->encPrivateKey != NULL) { destCertPair->encPrivateKey = SAL_CERT_KeyDup(mgrCtx, srcCertPair->encPrivateKey); if (destCertPair->encPrivateKey == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17342, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "enc KeyDup fail", 0, 0, 0, 0); return HITLS_CERT_ERR_X509_DUP; } } return HITLS_SUCCESS; } #endif CERT_Pair *SAL_CERT_PairDup(CERT_MgrCtx *mgrCtx, CERT_Pair *srcCertPair) { CERT_Pair *destCertPair = BSL_SAL_Calloc(1, sizeof(CERT_MgrCtx)); if (destCertPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16299, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } do { #ifdef HITLS_TLS_PROTO_TLCP11 if (TlcpCertPairDup(mgrCtx, srcCertPair, destCertPair) != HITLS_SUCCESS) { break; } #endif if (srcCertPair->cert != NULL) { destCertPair->cert = SAL_CERT_X509Dup(mgrCtx, srcCertPair->cert); if (destCertPair->cert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16300, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "X509Dup fail", 0, 0, 0, 0); break; } } if (srcCertPair->privateKey != NULL) { destCertPair->privateKey = SAL_CERT_KeyDup(mgrCtx, srcCertPair->privateKey); if (destCertPair->privateKey == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16301, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "KeyDup fail", 0, 0, 0, 0); break; } } if (srcCertPair->chain != NULL) { destCertPair->chain = SAL_CERT_ChainDup(mgrCtx, srcCertPair->chain); if (destCertPair->chain == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16302, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ChainDup fail", 0, 0, 0, 0); break; } } return destCertPair; } while (false); SAL_CERT_PairFree(mgrCtx, destCertPair); return NULL; } void SAL_CERT_PairClear(CERT_MgrCtx *mgrCtx, CERT_Pair *certPair) { if (mgrCtx == NULL || certPair == NULL) { return; } if (certPair->cert != NULL) { SAL_CERT_X509Free(certPair->cert); } #ifdef HITLS_TLS_PROTO_TLCP11 if (certPair->encCert != NULL) { SAL_CERT_X509Free(certPair->encCert); } if (certPair->encPrivateKey != NULL) { SAL_CERT_KeyFree(mgrCtx, certPair->encPrivateKey); } #endif if (certPair->privateKey != NULL) { SAL_CERT_KeyFree(mgrCtx, certPair->privateKey); } if (certPair->chain != NULL) { SAL_CERT_ChainFree(certPair->chain); } (void)memset_s(certPair, sizeof(CERT_Pair), 0, sizeof(CERT_Pair)); return; } void SAL_CERT_PairFree(CERT_MgrCtx *mgrCtx, CERT_Pair *certPair) { SAL_CERT_PairClear(mgrCtx, certPair); BSL_SAL_FREE(certPair); return; } int32_t SAL_CERT_HashDup(CERT_MgrCtx *destMgrCtx, CERT_MgrCtx *srcMgrCtx) { destMgrCtx->certPairs = BSL_HASH_Create(CERT_DEFAULT_HASH_BKT_SIZE, NULL, NULL, NULL, NULL); if (destMgrCtx->certPairs == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17347, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "BSL_HASH_Create fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } BSL_HASH_Hash *certPairs = srcMgrCtx->certPairs; BSL_HASH_Iterator iter = BSL_HASH_IterBegin(certPairs); while (iter != BSL_HASH_IterEnd(certPairs)) { uint32_t keyType = (uint32_t)BSL_HASH_HashIterKey(certPairs, iter); CERT_Pair *certPair = (CERT_Pair *)BSL_HASH_IterValue(certPairs, iter); if (certPair != NULL) { CERT_Pair *newCertPair = SAL_CERT_PairDup(srcMgrCtx, certPair); if (newCertPair == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_CERT_ERR_X509_DUP, BINLOG_ID17348, "x509dup fail"); } int32_t ret = BSL_HASH_Insert(destMgrCtx->certPairs, keyType, 0, (uintptr_t)newCertPair, sizeof(CERT_Pair)); if (ret != HITLS_SUCCESS) { SAL_CERT_PairFree(destMgrCtx, newCertPair); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID17349, "insert fail"); } } iter = BSL_HASH_IterNext(certPairs, iter); } return HITLS_SUCCESS; }
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/cert_adapt/cert_pair.c
C
unknown
6,242
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) #include <stdint.h> #include <string.h> #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls_cert_type.h" #include "hitls_type.h" #include "hitls_pki_x509.h" #include "bsl_list.h" #include "hitls_error.h" static int32_t BuildArrayFromList(HITLS_X509_List *list, HITLS_CERT_X509 **listArray, uint32_t *num) { HITLS_X509_Cert *elemt = NULL; int32_t i = 0; int32_t ret; for (elemt = BSL_LIST_GET_FIRST(list); elemt != NULL; elemt = BSL_LIST_GET_NEXT(list), i++) { int ref = 0; ret = HITLS_X509_CertCtrl(elemt, HITLS_X509_REF_UP, (void *)&ref, (int32_t)sizeof(int)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } listArray[i] = elemt; } *num = i; return HITLS_SUCCESS; } static int32_t BuildCertListFromCertArray(HITLS_CERT_X509 **listCert, uint32_t num, HITLS_X509_List **list) { int32_t ret = HITLS_SUCCESS; HITLS_X509_Cert **listArray = (HITLS_X509_Cert **)listCert; *list = BSL_LIST_New(num); if (*list == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } for (uint32_t i = 0; i < num; i++) { int ref = 0; ret = HITLS_X509_CertCtrl(listArray[i], HITLS_X509_REF_UP, (void *)&ref, (int32_t)sizeof(int)); if (ret != HITLS_SUCCESS) { BSL_LIST_FREE(*list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } ret = BSL_LIST_AddElement(*list, listArray[i], BSL_LIST_POS_END); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_LIST_FREE(*list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } } return HITLS_SUCCESS; } int32_t HITLS_X509_Adapt_BuildCertChain(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_X509 *cert, HITLS_CERT_X509 **list, uint32_t *num) { (void)config; *num = 0; HITLS_X509_List *certChain = NULL; int32_t ret = HITLS_X509_CertChainBuild((HITLS_X509_StoreCtx *)store, false, cert, &certChain); if (ret != HITLS_SUCCESS) { return ret; } ret = BuildArrayFromList(certChain, list, num); BSL_LIST_FREE(certChain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } int32_t HITLS_X509_Adapt_VerifyCertChain(HITLS_Ctx *ctx, HITLS_CERT_Store *store, HITLS_CERT_X509 **list, uint32_t num) { (void)ctx; /* The default user id as specified in GM/T 0009-2012 */ char sm2DefaultUserid[] = "1234567812345678"; HITLS_X509_List *certList = NULL; int32_t ret = BuildCertListFromCertArray(list, num, &certList); if (ret != HITLS_SUCCESS) { return ret; } int64_t sysTime = BSL_SAL_CurrentSysTimeGet(); if (sysTime == 0) { ret = HITLS_CERT_SELF_ADAPT_INVALID_TIME; BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_INVALID_TIME); goto EXIT; } ret = HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store, HITLS_X509_STORECTX_SET_TIME, &sysTime, sizeof(sysTime)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store, HITLS_X509_STORECTX_SET_VFY_SM2_USERID, sm2DefaultUserid, strlen(sm2DefaultUserid)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = HITLS_X509_CertVerify((HITLS_X509_StoreCtx *)store, certList); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: BSL_LIST_FREE(certList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree); return ret; } #endif /* defined(HITLS_TLS_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) */
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/hitls_x509_adapt/hitls_x509_cert_chain.c
C
unknown
4,346
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) #include <stdint.h> #include "securec.h" #include "crypt_eal_pkey.h" #include "hitls_error.h" #include "hitls_cert_type.h" #include "hitls_type.h" #include "hitls_pki_cert.h" #include "hitls_error.h" #include "bsl_err_internal.h" #include "tls_config.h" #include "cert_mgr_ctx.h" #include "config_type.h" int32_t HITLS_X509_Adapt_CertEncode(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, uint8_t *buf, uint32_t len, uint32_t *usedLen) { (void)ctx; *usedLen = 0; uint32_t encodeLen = 0; int32_t ret = HITLS_X509_CertCtrl((HITLS_X509_Cert *)cert, HITLS_X509_GET_ENCODELEN, &encodeLen, (int32_t)sizeof(uint32_t)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (len < encodeLen) { BSL_ERR_PUSH_ERROR(HITLS_INVALID_INPUT); return HITLS_INVALID_INPUT; } uint8_t *encodedBuff = NULL; ret = HITLS_X509_CertCtrl((HITLS_X509_Cert *)cert, HITLS_X509_GET_ENCODE, (void *)&encodedBuff, 0); if (ret != HITLS_SUCCESS) { return ret; } (void)memcpy_s(buf, len, encodedBuff, encodeLen); *usedLen = encodeLen; return ret; } #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_X509 *HITLS_CERT_ProviderCertParse(HITLS_Lib_Ctx *libCtx, const char *attrName, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format) { BSL_Buffer encodedCert = { NULL, 0 }; int ret; HITLS_X509_Cert *cert = NULL; switch (type) { case TLS_PARSE_TYPE_FILE: ret = HITLS_X509_ProviderCertParseFile(libCtx, attrName, format, (const char *)buf, &cert); break; case TLS_PARSE_TYPE_BUFF: encodedCert.data = (uint8_t *)(uintptr_t)buf; encodedCert.dataLen = len; ret = HITLS_X509_ProviderCertParseBuff(libCtx, attrName, format, &encodedCert, &cert); break; default: BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT); ret = HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT; break; } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return NULL; } return cert; } #else HITLS_CERT_X509 *HITLS_X509_Adapt_CertParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { (void)config; BSL_Buffer encodedCert = { NULL, 0 }; int ret; HITLS_X509_Cert *cert = NULL; switch (type) { case TLS_PARSE_TYPE_FILE: ret = HITLS_X509_CertParseFile(format, (const char *)buf, &cert); break; case TLS_PARSE_TYPE_BUFF: encodedCert.data = (uint8_t *)(uintptr_t)buf; encodedCert.dataLen = len; ret = HITLS_X509_CertParseBuff(format, &encodedCert, &cert); break; default: BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT); ret = HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT; break; } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return NULL; } return cert; } #endif HITLS_CERT_Chain *HITLS_X509_Adapt_BundleCertParse(HITLS_Lib_Ctx *libCtx, const char *attrName, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format) { BSL_Buffer encodedCert = { NULL, 0 }; int ret; HITLS_X509_List *certlist = NULL; switch (type) { case TLS_PARSE_TYPE_FILE: ret = HITLS_X509_ProviderCertParseBundleFile(libCtx, attrName, format, (const char *)buf, &certlist); break; case TLS_PARSE_TYPE_BUFF: encodedCert.data = (uint8_t *)(uintptr_t)buf; encodedCert.dataLen = len; ret = HITLS_X509_ProviderCertParseBundleBuff(libCtx, attrName, format, &encodedCert, &certlist); break; default: BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT); return NULL; } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return NULL; } return certlist; } void HITLS_X509_Adapt_CertFree(HITLS_CERT_X509 *cert) { HITLS_X509_CertFree(cert); } HITLS_CERT_X509 *HITLS_X509_Adapt_CertRef(HITLS_CERT_X509 *cert) { int ref = 0; int ret = HITLS_X509_CertCtrl(cert, HITLS_X509_REF_UP, (void *)&ref, (int32_t)sizeof(int)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return NULL; } return cert; } HITLS_CERT_X509 *HITLS_X509_Adapt_CertDup(HITLS_CERT_X509 *cert) { return HITLS_X509_Adapt_CertRef(cert); } static HITLS_SignHashAlgo BslCid2SignHashAlgo(HITLS_Config *config, BslCid signAlgId, BslCid hashAlgId) { uint32_t size = 0; const TLS_SigSchemeInfo *sigSchemeInfoList = ConfigGetSignatureSchemeInfoList(config, &size); for (size_t i = 0; i < size; i++) { if (sigSchemeInfoList[i].signHashAlgId == (int32_t)signAlgId && sigSchemeInfoList[i].hashAlgId == (int32_t)hashAlgId) { return sigSchemeInfoList[i].signatureScheme; } } return CERT_SIG_SCHEME_UNKNOWN; } static int32_t CertCtrlGetSignAlgo(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_SignHashAlgo *algSign) { BslCid signAlgCid = 0; BslCid hashCid = 0; *algSign = CERT_SIG_SCHEME_UNKNOWN; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SIGNALG, &signAlgCid, sizeof(BslCid)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SIGN_MDALG, &hashCid, sizeof(BslCid)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *algSign = BslCid2SignHashAlgo(config, signAlgCid, hashCid); return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_TLCP11) || defined(HITLS_TLS_CONFIG_KEY_USAGE) static int32_t CertCheckKeyUsage(HITLS_Config *config, HITLS_CERT_X509 *cert, uint32_t inKeyUsage, bool *res) { (void)config; uint32_t keyUsage = 0; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_KUSAGE, &keyUsage, sizeof(uint32_t)); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (keyUsage == HITLS_X509_EXT_KU_NONE) { #ifdef HITLS_TLS_PROTO_TLCP11 // Key usage must be present, otherwise the chain is broken. if (config == NULL) { return HITLS_INVALID_INPUT; } if (config->maxVersion == HITLS_VERSION_TLCP_DTLCP11) { BSL_ERR_PUSH_ERROR(HITLS_CERT_ERR_NO_KEYUSAGE); return HITLS_CERT_ERR_NO_KEYUSAGE; } #endif *res = true; return HITLS_SUCCESS; } *res = (keyUsage & inKeyUsage) != 0; return HITLS_SUCCESS; } #endif int32_t HITLS_X509_Adapt_CertCtrl(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_CtrlCmd cmd, void *input, void *output) { (void)input; int32_t ret = HITLS_SUCCESS; switch (cmd) { case CERT_CTRL_GET_ENCODE_LEN: ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ENCODELEN, output, (uint32_t)sizeof(int32_t)); break; case CERT_CTRL_GET_PUB_KEY: ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, output, (uint32_t)sizeof(CRYPT_EAL_PkeyPub *)); break; case CERT_CTRL_GET_SIGN_ALGO: return CertCtrlGetSignAlgo(config, cert, (HITLS_SignHashAlgo *)output); #if defined(HITLS_TLS_PROTO_TLCP11) || defined(HITLS_TLS_CONFIG_KEY_USAGE) case CERT_KEY_CTRL_IS_KEYENC_USAGE: return CertCheckKeyUsage(config, cert, HITLS_X509_EXT_KU_KEY_ENCIPHERMENT, (bool *)output); case CERT_KEY_CTRL_IS_DIGITAL_SIGN_USAGE: return CertCheckKeyUsage(config, cert, HITLS_X509_EXT_KU_DIGITAL_SIGN, (bool *)output); case CERT_KEY_CTRL_IS_KEY_CERT_SIGN_USAGE: return CertCheckKeyUsage(config, cert, HITLS_X509_EXT_KU_KEY_CERT_SIGN, (bool *)output); case CERT_KEY_CTRL_IS_KEY_AGREEMENT_USAGE: return CertCheckKeyUsage(config, cert, HITLS_X509_EXT_KU_KEY_AGREEMENT, (bool *)output); case CERT_KEY_CTRL_IS_DATA_ENC_USAGE: return CertCheckKeyUsage(config, cert, HITLS_X509_EXT_KU_DATA_ENCIPHERMENT, (bool *)output); case CERT_KEY_CTRL_IS_NON_REPUDIATION_USAGE: return CertCheckKeyUsage(config, cert, HITLS_X509_EXT_KU_NON_REPUDIATION, (bool *)output); #endif case CERT_CTRL_GET_ENCODE_SUBJECT_DN: ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ENCODE_SUBJECT_DN, output, sizeof(BSL_Buffer *)); break; case CERT_CTRL_IS_SELF_SIGNED: return HITLS_X509_CertCtrl(cert, HITLS_X509_IS_SELF_SIGNED, (bool *)output, (uint32_t)sizeof(bool)); default: BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_ERR); return HITLS_CERT_SELF_ADAPT_ERR; } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif /* defined(HITLS_TLS_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) */
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/hitls_x509_adapt/hitls_x509_cert_magr.c
C
unknown
9,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_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) #include <stdint.h> #include <string.h> #include "bsl_err_internal.h" #include "crypt_errno.h" #include "hitls_cert_type.h" #include "hitls_type.h" #include "hitls_pki_x509.h" #include "hitls_pki_crl.h" #include "hitls_cert_local.h" #include "hitls_error.h" #include "hitls_x509_adapt.h" HITLS_CERT_Store *HITLS_X509_Adapt_StoreNew(void) { return (HITLS_CERT_Store *)HITLS_X509_StoreCtxNew(); } HITLS_CERT_Store *HITLS_X509_Adapt_StoreDup(HITLS_CERT_Store *store) { int references = 0; int32_t ret = HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store, HITLS_X509_STORECTX_REF_UP, &references, sizeof(int)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return NULL; } return store; } void HITLS_X509_Adapt_StoreFree(HITLS_CERT_Store *store) { HITLS_X509_StoreCtxFree(store); } int32_t HITLS_X509_Adapt_StoreCtrl(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_CtrlCmd cmd, void *input, void *output) { (void)config; (void)output; int32_t value1 = 0; uint64_t value2 = 0; int32_t ret = 0; switch (cmd) { case CERT_STORE_CTRL_SET_VERIFY_DEPTH: if (*(int64_t *)input > INT32_MAX) { return HITLS_CERT_SELF_ADAPT_ERR; } value1 = *(int64_t *)input; return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_DEPTH, &value1, sizeof(int32_t)); case CERT_STORE_CTRL_GET_VERIFY_DEPTH: return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_GET_PARAM_DEPTH, output, sizeof(int32_t)); case CERT_STORE_CTRL_SET_VERIFY_FLAGS: if (*(int64_t *)input > UINT32_MAX || *(int64_t *)input < 0) { return HITLS_CERT_SELF_ADAPT_ERR; } return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_FLAGS, (int64_t *)input, sizeof(uint64_t)); case CERT_STORE_CTRL_GET_VERIFY_FLAGS: ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_GET_PARAM_FLAGS, &value2, sizeof(uint64_t)); *(uint32_t *)output = (uint32_t)value2; return ret; case CERT_STORE_CTRL_ADD_CERT_LIST: return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SHALLOW_COPY_SET_CA, input, sizeof(HITLS_X509_Cert)); case CERT_STORE_CTRL_ADD_CRL_LIST: { /* Input is a HITLS_CERT_CRLList (BSL_LIST), need to iterate and add each CRL */ HITLS_CERT_CRLList *crlList = (HITLS_CERT_CRLList *)input; if (crlList == NULL) { return HITLS_CERT_SELF_ADAPT_ERR; } HITLS_X509_Crl *tempCrl = (HITLS_X509_Crl *)BSL_LIST_GET_FIRST(crlList); while (tempCrl != NULL) { ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_CRL, tempCrl, 0); if (ret != CRYPT_SUCCESS) { return ret; } tempCrl = (HITLS_X509_Crl *)BSL_LIST_GET_NEXT(crlList); } int64_t setFlag = HITLS_X509_VFY_FLAG_CRL_ALL; return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_FLAGS, &setFlag, sizeof(int64_t)); } case CERT_STORE_CTRL_CLEAR_CRL_LIST: return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_CLEAR_CRL, NULL, 0); case CERT_STORE_CTRL_ADD_CA_PATH: return HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_ADD_CA_PATH, input, strlen(input)); default: return HITLS_CERT_SELF_ADAPT_ERR; } } #endif /* defined(HITLS_TLS_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) */
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/hitls_x509_adapt/hitls_x509_cert_store.c
C
unknown
4,302
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <string.h> #include "hitls_build.h" #include "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_cert_type.h" #include "bsl_uio.h" #include "bsl_sal.h" #include "hitls_pki_crl.h" #include "hitls_pki_errno.h" #include "hitls_x509_adapt.h" static int32_t LoadCrlFromFile(const char *path, HITLS_ParseFormat format, HITLS_X509_List **crlList) { return HITLS_X509_CrlParseBundleFile(format, path, crlList); } static int32_t LoadCrlFromBuffer(const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format, HITLS_X509_List **crlList) { BSL_Buffer buffer = {(uint8_t *)(uintptr_t)buf, bufLen}; return HITLS_X509_CrlParseBundleBuff(format, &buffer, crlList); } HITLS_CERT_CRLList *HITLS_X509_Adapt_CrlParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { (void)config; /* config parameter not used for CRL parsing */ if (buf == NULL || len == 0) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return NULL; } HITLS_X509_List *crlList = NULL; int32_t ret; if (type == TLS_PARSE_TYPE_FILE) { ret = LoadCrlFromFile((const char *)buf, format, &crlList); } else if (type == TLS_PARSE_TYPE_BUFF) { ret = LoadCrlFromBuffer(buf, len, format, &crlList); } else { BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return NULL; } if (ret != HITLS_PKI_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16572, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CRL parse failed, ret = %d", ret, 0, 0, 0); return NULL; } return (HITLS_CERT_CRLList *)crlList; } void HITLS_X509_Adapt_CrlFree(HITLS_CERT_CRLList *crlList) { if (crlList != NULL) { HITLS_X509_List *list = (HITLS_X509_List *)crlList; BSL_LIST_FREE(list, (BSL_LIST_PFUNC_FREE)HITLS_X509_CrlFree); } }
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/hitls_x509_adapt/hitls_x509_crl_magr.c
C
unknown
2,532
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) #include <stdio.h> #include <string.h> #include "crypt_types.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "hitls_error.h" #include "hitls_type.h" #include "hitls_cert_type.h" #include "hitls_crypt_type.h" #include "crypt_algid.h" #include "crypt_eal_pkey.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "eal_md_local.h" #include "hitls_pki_cert.h" #include "tls.h" #ifdef HITLS_TLS_FEATURE_PROVIDER static int32_t SetMdAttr(CRYPT_EAL_PkeyCtx *ctx, const char *attrName) { CRYPT_PKEY_AlgId id = CRYPT_EAL_PkeyGetId(ctx); bool supportUnloadMd = id == CRYPT_PKEY_RSA || id == CRYPT_PKEY_ECDSA || id == CRYPT_PKEY_DSA; if (attrName == NULL || strlen(attrName) == 0 || supportUnloadMd == false) { return CRYPT_SUCCESS; } BSL_Param param[] = { {.key = CRYPT_PARAM_MD_ATTR, .valueType = BSL_PARAM_TYPE_UTF8_STR, .value = (void *)(uintptr_t)attrName, .valueLen = strlen(attrName), .useLen = 0}, BSL_PARAM_END }; return CRYPT_EAL_PkeySetParaEx(ctx, param); } #endif static int32_t SetPkeySignParam(CRYPT_EAL_PkeyCtx *ctx, HITLS_SignAlgo signAlgo, int32_t mdAlgId, const char *attrName) { (void)attrName; #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = SetMdAttr(ctx, attrName); if (ret != CRYPT_SUCCESS) { return ret; } #endif if (signAlgo == HITLS_SIGN_RSA_PKCS1_V15) { int32_t pad = mdAlgId; return CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &pad, sizeof(pad)); } else if (signAlgo == HITLS_SIGN_RSA_PSS) { int32_t saltLen = CRYPT_RSA_SALTLEN_TYPE_HASHLEN; BSL_Param pssParam[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &mdAlgId, sizeof(mdAlgId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &mdAlgId, sizeof(mdAlgId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &saltLen, sizeof(saltLen), 0}, BSL_PARAM_END}; return CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PSS, pssParam, 0); } else if (signAlgo == HITLS_SIGN_SM2) { /* The default user id as specified in GM/T 0009-2012 */ char sm2DefaultUserid[] = "1234567812345678"; return CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_SM2_USER_ID, sm2DefaultUserid, strlen(sm2DefaultUserid)); } return HITLS_SUCCESS; } int32_t HITLS_X509_Adapt_CreateSign(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) { (void)ctx; if (SetPkeySignParam(key, signAlgo, hashAlgo, ATTRIBUTE_FROM_CTX(ctx)) != HITLS_SUCCESS) { return HITLS_CERT_SELF_ADAPT_ERR; } return CRYPT_EAL_PkeySign(key, (CRYPT_MD_AlgId)hashAlgo, data, dataLen, sign, signLen); } int32_t HITLS_X509_Adapt_VerifySign(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) { (void)ctx; if (SetPkeySignParam(key, signAlgo, hashAlgo, ATTRIBUTE_FROM_CTX(ctx)) != HITLS_SUCCESS) { return HITLS_CERT_SELF_ADAPT_ERR; } return CRYPT_EAL_PkeyVerify(key, (CRYPT_MD_AlgId)hashAlgo, data, dataLen, sign, signLen); } #if defined(HITLS_TLS_SUITE_KX_RSA) || defined(HITLS_TLS_PROTO_TLCP11) static int32_t CertSetRsaEncryptionScheme(CRYPT_EAL_PkeyCtx *ctx) { int32_t pad = CRYPT_MD_SHA256; return CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_RSAES_PKCSV15, &pad, sizeof(pad)); } /* only support rsa pkcs1.5 */ int32_t HITLS_X509_Adapt_Encrypt(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { (void)ctx; #ifdef HITLS_TLS_FEATURE_PROVIDER if (SetMdAttr(key, ATTRIBUTE_FROM_CTX(ctx)) != HITLS_SUCCESS) { return HITLS_CERT_SELF_ADAPT_ERR; } #endif if (CRYPT_EAL_PkeyGetId(key) == CRYPT_PKEY_RSA && CertSetRsaEncryptionScheme(key) != HITLS_SUCCESS) { return HITLS_CERT_SELF_ADAPT_ERR; } return CRYPT_EAL_PkeyEncrypt(key, in, inLen, out, outLen); } int32_t HITLS_X509_Adapt_Decrypt(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { (void)ctx; #ifdef HITLS_TLS_FEATURE_PROVIDER if (SetMdAttr(key, ATTRIBUTE_FROM_CTX(ctx)) != HITLS_SUCCESS) { return HITLS_CERT_SELF_ADAPT_ERR; } #endif if (CRYPT_EAL_PkeyGetId(key) == CRYPT_PKEY_RSA && CertSetRsaEncryptionScheme(key) != HITLS_SUCCESS) { return HITLS_CERT_SELF_ADAPT_ERR; } return CRYPT_EAL_PkeyDecrypt(key, in, inLen, out, outLen); } #endif int32_t HITLS_X509_Adapt_CheckPrivateKey(const HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_Key *key) { (void)config; CRYPT_EAL_PkeyCtx *ealPubKey = NULL; CRYPT_EAL_PkeyCtx *ealPrivKey = (CRYPT_EAL_PkeyCtx *)key; int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &ealPubKey, 0); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_PkeyPairCheck(ealPubKey, ealPrivKey); CRYPT_EAL_PkeyFreeCtx(ealPubKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif /* defined(HITLS_TLS_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) */
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/hitls_x509_adapt/hitls_x509_crypto.c
C
unknown
5,969
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stdint.h> #include <stddef.h> #include "hitls_error.h" #include "hitls_cert_reg.h" #include "hitls_x509_adapt.h" int32_t HITLS_CertMethodInit(void) { #ifdef HITLS_TLS_CALLBACK_CERT HITLS_CERT_MgrMethod mgr = { .certStoreNew = HITLS_X509_Adapt_StoreNew, .certStoreDup = HITLS_X509_Adapt_StoreDup, .certStoreFree = HITLS_X509_Adapt_StoreFree, .certStoreCtrl = HITLS_X509_Adapt_StoreCtrl, .buildCertChain = HITLS_X509_Adapt_BuildCertChain, .verifyCertChain = HITLS_X509_Adapt_VerifyCertChain, .certEncode = HITLS_X509_Adapt_CertEncode, .certParse = HITLS_X509_Adapt_CertParse, .certDup = HITLS_X509_Adapt_CertDup, .certRef = HITLS_X509_Adapt_CertRef, .certFree = HITLS_X509_Adapt_CertFree, .certCtrl = HITLS_X509_Adapt_CertCtrl, .keyParse = HITLS_X509_Adapt_KeyParse, .keyDup = HITLS_X509_Adapt_KeyDup, .keyFree = HITLS_X509_Adapt_KeyFree, .keyCtrl = HITLS_X509_Adapt_KeyCtrl, .createSign = HITLS_X509_Adapt_CreateSign, .verifySign = HITLS_X509_Adapt_VerifySign, #if defined(HITLS_TLS_SUITE_KX_RSA) || defined(HITLS_TLS_PROTO_TLCP11) .encrypt = HITLS_X509_Adapt_Encrypt, .decrypt = HITLS_X509_Adapt_Decrypt, #endif .checkPrivateKey = HITLS_X509_Adapt_CheckPrivateKey, }; return HITLS_CERT_RegisterMgrMethod(&mgr); #else return HITLS_SUCCESS; #endif } void HITLS_CertMethodDeinit(void) { #ifdef HITLS_TLS_CALLBACK_CERT HITLS_CERT_DeinitMgrMethod(); #endif }
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/hitls_x509_adapt/hitls_x509_init.c
C
unknown
2,146
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) #include <stdint.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_types.h" #include "bsl_err_internal.h" #include "hitls_x509_adapt.h" #include "crypt_eal_codecs.h" #include "crypt_errno.h" #include "hitls_cert.h" #include "hitls_cert_type.h" #include "hitls_error.h" #include "hitls_type.h" #include "crypt_eal_pkey.h" #include "hitls_crypt_type.h" #include "config_type.h" #include "tls_config.h" #include "cert_mgr_ctx.h" static int32_t GetPassByCb(HITLS_PasswordCb passWordCb, void *passWordCbUserData, char *pass, int32_t *passLen) { if (pass == NULL || passLen == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } int32_t len = 0; if (passWordCb != NULL) { len = passWordCb(pass, *passLen, 0, passWordCbUserData); if (len < 0) { BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_ERR); return HITLS_CERT_SELF_ADAPT_ERR; } } else { if (passWordCbUserData != NULL) { uint32_t userDataLen = BSL_SAL_Strnlen((const char *)passWordCbUserData, *passLen); if (userDataLen == 0 || userDataLen == (uint32_t)*passLen) { BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_ERR); return HITLS_CERT_SELF_ADAPT_ERR; } (void)memcpy_s(pass, *passLen, (char *)passWordCbUserData, userDataLen + 1); len = userDataLen; } } *passLen = len; return HITLS_SUCCESS; } static int32_t GetPrivKeyPassword(HITLS_Config *config, uint8_t *pwd, int32_t *pwdLen) { HITLS_PasswordCb pwCb = HITLS_CFG_GetDefaultPasswordCb(config); void *userData = HITLS_CFG_GetDefaultPasswordCbUserdata(config); int32_t len = *pwdLen; int32_t ret = GetPassByCb(pwCb, userData, (char *)pwd, pwdLen); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); (void)memset_s(pwd, len, 0, len); } return ret; } #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_Key *HITLS_X509_Adapt_ProviderKeyParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format, const char *encodeType) { HITLS_Lib_Ctx *libCtx = LIBCTX_FROM_CONFIG(config); const char *attrName = ATTRIBUTE_FROM_CONFIG(config); int32_t ret; BSL_Buffer encode = {0}; HITLS_CERT_Key *ealPriKey = NULL; uint8_t pwd[MAX_PASS_LEN] = { 0 }; BSL_Buffer pwdBuff = {pwd, sizeof(pwd)}; (void)GetPrivKeyPassword(config, pwdBuff.data, (int32_t *)&pwdBuff.dataLen); switch (type) { case TLS_PARSE_TYPE_FILE: ret = CRYPT_EAL_ProviderDecodeFileKey(libCtx, attrName, BSL_CID_UNKNOWN, format, encodeType, (const char *)buf, &pwdBuff, (CRYPT_EAL_PkeyCtx **)&ealPriKey); break; case TLS_PARSE_TYPE_BUFF: encode.data = (uint8_t *)(uintptr_t)buf; encode.dataLen = len; ret = CRYPT_EAL_ProviderDecodeBuffKey(libCtx, attrName, BSL_CID_UNKNOWN, format, encodeType, &encode, &pwdBuff, (CRYPT_EAL_PkeyCtx **)&ealPriKey); break; default: BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT); (void)memset_s(pwd, MAX_PASS_LEN, 0, MAX_PASS_LEN); return NULL; } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } (void)memset_s(pwd, MAX_PASS_LEN, 0, MAX_PASS_LEN); return ealPriKey; } #else HITLS_CERT_Key *HITLS_X509_Adapt_KeyParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { (void)config; int32_t ret; BSL_Buffer encode = {0}; HITLS_CERT_Key *ealPriKey = NULL; uint8_t pwd[MAX_PASS_LEN] = { 0 }; int32_t pwdLen = (int32_t)sizeof(pwd); (void)GetPrivKeyPassword(config, pwd, &pwdLen); switch (type) { case TLS_PARSE_TYPE_FILE: ret = CRYPT_EAL_DecodeFileKey(format, CRYPT_ENCDEC_UNKNOW, (const char *)buf, pwd, pwdLen, (CRYPT_EAL_PkeyCtx **)&ealPriKey); break; case TLS_PARSE_TYPE_BUFF: encode.data = (uint8_t *)(uintptr_t)buf; encode.dataLen = len; ret = CRYPT_EAL_DecodeBuffKey(format, CRYPT_ENCDEC_UNKNOW, &encode, pwd, pwdLen, (CRYPT_EAL_PkeyCtx **)&ealPriKey); break; default: BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_UNSUPPORT_FORMAT); (void)memset_s(pwd, MAX_PASS_LEN, 0, MAX_PASS_LEN); return NULL; } if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } (void)memset_s(pwd, MAX_PASS_LEN, 0, MAX_PASS_LEN); return ealPriKey; } #endif HITLS_CERT_Key *HITLS_X509_Adapt_KeyDup(HITLS_CERT_Key *key) { return (HITLS_CERT_Key *)CRYPT_EAL_PkeyDupCtx(key); } void HITLS_X509_Adapt_KeyFree(HITLS_CERT_Key *key) { CRYPT_EAL_PkeyFreeCtx(key); } static HITLS_NamedGroup GetCurveNameByKey(HITLS_Config *config, const CRYPT_EAL_PkeyCtx *key) { CRYPT_PKEY_ParaId paraId = CRYPT_EAL_PkeyGetParaId(key); if (paraId == CRYPT_PKEY_PARAID_MAX) { return HITLS_NAMED_GROUP_BUTT; } uint32_t size = 0; const TLS_GroupInfo *groupInfoList = ConfigGetGroupInfoList(config, &size); for (size_t i = 0; i < size; i++) { if (groupInfoList[i].paraId == (int32_t)paraId) { return groupInfoList[i].groupId; } } return HITLS_NAMED_GROUP_BUTT; } static HITLS_CERT_KeyType CertKeyAlgId2KeyType(CRYPT_EAL_PkeyCtx *pkey) { CRYPT_PKEY_AlgId cid = CRYPT_EAL_PkeyGetId(pkey); if (cid == CRYPT_PKEY_RSA) { CRYPT_RsaPadType padType = 0; if (CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType)) != CRYPT_SUCCESS) { return TLS_CERT_KEY_TYPE_UNKNOWN; } if (padType == CRYPT_EMSA_PSS) { return TLS_CERT_KEY_TYPE_RSA_PSS; } } return (HITLS_CERT_KeyType)cid; } int32_t HITLS_X509_Adapt_KeyCtrl(HITLS_Config *config, HITLS_CERT_Key *key, HITLS_CERT_CtrlCmd cmd, void *input, void *output) { (void)input; int32_t ret = HITLS_SUCCESS; switch (cmd) { case CERT_KEY_CTRL_GET_SIGN_LEN: *(uint32_t *)output = CRYPT_EAL_PkeyGetSignLen((const CRYPT_EAL_PkeyCtx *)key); break; case CERT_KEY_CTRL_GET_TYPE: *(HITLS_CERT_KeyType *)output = CertKeyAlgId2KeyType(key); break; case CERT_KEY_CTRL_GET_CURVE_NAME: *(HITLS_NamedGroup *)output = GetCurveNameByKey(config, key); break; case CERT_KEY_CTRL_GET_POINT_FORMAT: /* Currently only uncompressed is used */ *(HITLS_ECPointFormat *)output = HITLS_POINT_FORMAT_UNCOMPRESSED; break; case CERT_KEY_CTRL_GET_SECBITS: *(int32_t *)output = CRYPT_EAL_PkeyGetSecurityBits(key); break; case CERT_KEY_CTRL_GET_PARAM_ID: *(int32_t *)output = CRYPT_EAL_PkeyGetParaId(key); break; default: BSL_ERR_PUSH_ERROR(HITLS_CERT_SELF_ADAPT_ERR); ret = HITLS_CERT_SELF_ADAPT_ERR; break; } return ret; } #endif /* defined(HITLS_TLS_CALLBACK_CERT) || defined(HITLS_TLS_FEATURE_PROVIDER) */
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/hitls_x509_adapt/hitls_x509_pkey_magr.c
C
unknown
7,886
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CERT_H #define CERT_H #include <stdint.h> #include "hitls_type.h" #include "hitls_cert_type.h" #include "cipher_suite.h" #include "cert_mgr.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif #define TLS_DEFAULT_VERIFY_DEPTH 20u #define MAX_PASS_LEN 256 /* tls.handshake.certificate_length Length of a label */ #define CERT_LEN_TAG_SIZE 3u /* Used to transfer certificate data in ASN.1 DER format. */ typedef struct CertItem { uint32_t dataSize; /* Data length */ uint8_t *data; /* Data content */ struct CertItem *next; } CERT_Item; /* Information used to describe the expected certificate */ typedef struct { /* The server must select the certificate matching the cipher suite. The client has no such restriction. */ CERT_Type certType; uint16_t *signSchemeList; /* certificate signature algorithm list */ uint32_t signSchemeNum; /* number of certificate signature algorithms */ uint16_t *ellipticCurveList; /* EC curve ID list */ uint32_t ellipticCurveNum; /* number of EC curve IDs */ uint8_t *ecPointFormatList; /* EC point format list */ uint32_t ecPointFormatNum; /* number of EC point formats */ HITLS_TrustedCAList *caList; /* trusted CA list */ } CERT_ExpectInfo; /** * @ingroup hitls_cert_type * @brief used to transfer the signature parameter */ typedef struct { HITLS_SignAlgo signAlgo; /* signature algorithm */ HITLS_HashAlgo hashAlgo; /* hash algorithm */ const uint8_t *data; /* signed data */ uint32_t dataLen; /* length of the signed data */ uint8_t *sign; /* sign */ uint32_t signLen; /* signature length */ } CERT_SignParam; /** * @brief Check the certificate information. * * @param ctx [IN] TLS context * @param expectCertInfo [IN] Expected certificate information * @param cert [IN] Certificate * @param isNegotiateSignAlgo [IN] Indicates whether to select the signature algorithm used in handshake messages. * @param signCheck [IN] Indicates whether to check the certificate signature information. * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK No callback is set. * @retval HITLS_CERT_CTRL_ERR_GET_PUB_KEY Failed to obtain the public key. * @retval HITLS_CERT_KEY_CTRL_ERR_GET_TYPE Failed to obtain the public key type. * @retval HITLS_CERT_ERR_UNSUPPORT_CERT_TYPE The certificate type does not match. * @retval HITLS_CERT_ERR_NO_SIGN_SCHEME_MATCH signature algorithm mismatch * @retval HITLS_CERT_ERR_NO_CURVE_MATCH elliptic curve mismatch * @retval HITLS_CERT_ERR_NO_POINT_FORMAT_MATCH Point format mismatch */ int32_t SAL_CERT_CheckCertInfo(HITLS_Ctx *ctx, const CERT_ExpectInfo *expectCertInfo, HITLS_CERT_X509 *cert, bool isNegotiateSignAlgo, bool signCheck); /** * @brief Select the certificate chain to be sent to the peer end. * * @param ctx [IN] tls Context * @param info [IN] Expected certificate information * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK No callback is set. * @retval HITLS_CERT_ERR_SELECT_CERTIFICATE Failed to select the certificate. */ int32_t SAL_CERT_SelectCertByInfo(HITLS_Ctx *ctx, CERT_ExpectInfo *info); /** * @brief Encode the certificate chain in ASN.1 DER format. * * @param ctx [IN] tls Context * @param pkt [IN/OUT] Context for packing * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK No callback is set. * @retval HITLS_CERT_ERR_BUILD_CHAIN Failed to assemble the certificate chain. * @retval HITLS_CERT_CTRL_ERR_GET_ENCODE_LEN Failed to obtain the encoding length. * @retval HITLS_CERT_ERR_ENCODE_CERT Certificate encoding failed. */ int32_t SAL_CERT_EncodeCertChain(HITLS_Ctx *ctx, PackPacket *pkt); /** * @brief Decode the certificate in ASN.1 DER format. * * @param ctx [IN] tls Context * @param item [IN] Original certificate data, which is a linked list. Each node indicates a certificate. * @param certPair [OUT] Certificate chain * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK No callback is set. * @retval HITLS_MEMALLOC_FAIL Insufficient Memory * @retval HITLS_CERT_ERR_PARSE_MSG Failed to parse the certificate data. */ int32_t SAL_CERT_ParseCertChain(HITLS_Ctx *ctx, CERT_Item *item, CERT_Pair **certPair); /** * @brief Verify the certificate chain. * * @param ctx [IN] tls Context * @param certPair [IN] Certificate chain * @param isGmEncCert [IN] Indicates whether to verify the certificate chain of the encrypted certificate * of the TLCP. The value is always false * when the TLCP protocol is not used. * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK No callback is set. * @retval HITLS_MEMALLOC_FAIL Insufficient Memory * @retval HITLS_CERT_ERR_VERIFY_CERT_CHAIN Failed to verify the certificate chain. */ int32_t SAL_CERT_VerifyCertChain(HITLS_Ctx *ctx, CERT_Pair *certPair, bool isTlcpEncCert); /** * @brief Obtain the maximum signature length. * * @param config [IN] TLS link configuration * @param key [IN] Certificate private key * * @return Signature length */ uint32_t SAL_CERT_GetSignMaxLen(HITLS_Config *config, HITLS_CERT_Key *key); /** * @brief Sign with the certificate private key. * * @param ctx [IN] tls Context * @param key [IN] Certificate private key * @param signParam [IN/OUT] Signature information * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK No callback is set. * @retval HITLS_CERT_ERR_CREATE_SIGN Signing failed. */ int32_t SAL_CERT_CreateSign(HITLS_Ctx *ctx, HITLS_CERT_Key *key, CERT_SignParam *signParam); /** * @brief Use the certificate public key to verify the signature. * * @param ctx [IN] tls Context * @param key [IN] Certificate public key * @param signParam [IN] Signature information * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_UNREGISTERED_CALLBACK No callback is set. * @retval HITLS_CERT_ERR_VERIFY_SIGN Failed to verify the signature. */ int32_t SAL_CERT_VerifySign(HITLS_Ctx *ctx, HITLS_CERT_Key *key, CERT_SignParam *signParam); /** * @ingroup hitls_cert_reg * @brief Encrypted by the certificate public key, which is used for the RSA cipher suite. * * @param ctx [IN] tls Context * @param key [IN] Certificate public key * @param in [IN] Plaintext * @param inLen [IN] length of plaintext * @param out [IN] Ciphertext * @param outLen [IN/OUT] IN: Maximum length of the ciphertext padding. OUT: Length of the ciphertext * * @retval HITLS_SUCCESS succeeded */ int32_t SAL_CERT_KeyEncrypt(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, which is used for the RSA cipher suite. * * @param ctx [IN] tls Context * @param key [IN] Certificate private key * @param in [IN] Ciphertext * @param inLen [IN] length of ciphertext * @param out [IN] Plaintext * @param outLen [IN/OUT] IN: Maximum length of plaintext padding. OUT: Plaintext length * * @retval HITLS_SUCCESS succeeded */ int32_t SAL_CERT_KeyDecrypt(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @brief Obtain the default signature hash algorithm based on the certificate public key type. * * @param keyType [IN] Certificate public key type * * @retval Default signature hash algorithm */ HITLS_SignHashAlgo SAL_CERT_GetDefaultSignHashAlgo(HITLS_CERT_KeyType keyType); /** * @ingroup hitls_cert_reg * @brief Encoded content of the TLCP encryption certificate obtained by the server. * * @param ctx [IN] tls Context * @param outLen [OUT] OUT: length after encoding * * @retval Encoded content */ uint8_t *SAL_CERT_SrvrGmEncodeEncCert(HITLS_Ctx *ctx, uint32_t *useLen); /** * @ingroup hitls_cert_reg * @brief The client obtains the encoded content of the TLCP encryption certificate. * * @param ctx [IN] tls Context * @param peerCert [IN] Peer certificate information * @param outLen [OUT] OUT: length after encoding * * @retval Encoded content */ uint8_t *SAL_CERT_ClntGmEncodeEncCert(HITLS_Ctx *ctx, CERT_Pair *peerCert, uint32_t *useLen); /** * @ingroup hitls_cert_reg * @brief Check whether the certificate is an encrypted certificate, a digital signature, * or a permission to issue the certificate. * * @param ctx [IN] tls Context * @param cert [IN] Certificate to be verified * * @retval true indicates that is the encryption certificate. */ bool SAL_CERT_CheckCertKeyUsage(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, HITLS_CERT_CtrlCmd keyusage); /** * @brief get cert key type based on signScheme * * @param signScheme [IN] signature algorithm * * @retval cert key type */ HITLS_CERT_KeyType SAL_CERT_SignScheme2CertKeyType(const HITLS_Ctx *ctx, HITLS_SignHashAlgo signScheme); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/include/cert.h
C
unknown
10,096
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CERT_METHOD_H #define CERT_METHOD_H #include <stdint.h> #include "hitls_cert_type.h" #include "tls_config.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Create a certificate store. * * @param mgrCtx [IN] Certificate management struct * * @return Certificate store */ HITLS_CERT_Store *SAL_CERT_StoreNew(const CERT_MgrCtx *mgrCtx); /** * @brief Copy the certificate store. * * @param mgrCtx [IN] Certificate management struct * @param store [IN] Certificate store * * @return Certificate store */ HITLS_CERT_Store *SAL_CERT_StoreDup(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store); /** * @brief Release the certificate store. * * @param mgrCtx [IN] Certificate management struct * @param store [IN] Certificate store * * @return void */ void SAL_CERT_StoreFree(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store); /** * @brief Construct the certificate chain. * * @param config [IN] TLS link configuration * @param store [IN] Certificate store * @param cert [IN] Device certificate * @param certList [OUT] Certificate chain * @param num [IN/OUT] IN: length of array OUT: length of certificate chain * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_BuildChain(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_X509 *cert, HITLS_CERT_X509 **certList, uint32_t *num); /** * @brief Verify the certificate chain. * * @param config [IN] TLS link configuration * @param store [IN] Certificate store * @param certList [IN] Certificate chain * @param num [IN] length of certificate chain * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_VerifyChain(HITLS_Ctx *ctx, HITLS_CERT_Store *store, HITLS_CERT_X509 **certList, uint32_t num); /** * @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] buffer length * @param usedLen [OUT] Data length * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_X509Encode(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, uint8_t *buf, uint32_t len, uint32_t *usedLen); /** * @brief Parse the bundle certificate to list. * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param config [IN] TLS link configuration * @param buf [IN] Certificate encoding data * @param len [IN] Data length * @param type [IN] Data type * @param format [IN] Data format * * @return certificate list */ HITLS_CERT_Chain *SAL_CERT_X509ParseBundleFile(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); /** * @brief Parse the certificate. * * @param libCtx [IN] library context for provider * @param attrName [IN] attribute name of the provider, maybe NULL * @param config [IN] TLS link configuration * @param buf [IN] Certificate encoding data * @param len [IN] Data length * @param type [IN] Data type * @param format [IN] Data format * * @return Certificate */ HITLS_CERT_X509 *SAL_CERT_X509Parse(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); /** * @brief Copy the certificate. * * @param mgrCtx [IN] Certificate management struct * @param cert [IN] Certificate * * @return Certificate */ HITLS_CERT_X509 *SAL_CERT_X509Dup(const CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert); /** * @brief Certificate reference increments by one. * * @param mgrCtx [IN] Certificate management struct * @param cert [IN] Certificate * * @return Certificate */ HITLS_CERT_X509 *SAL_CERT_X509Ref(const CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert); /** * @brief Release the certificate. * * @param cert [IN] Certificate * * @return void */ void SAL_CERT_X509Free(HITLS_CERT_X509 *cert); /** * @brief Parse the key. * * @param config [IN] TLS link configuration * @param buf [IN] Key coded data * @param len [IN] Data length * @param type [IN] Data type * @param format [IN] Data format * @param encodeType [IN] Data encode type * * @return Key */ HITLS_CERT_Key *SAL_CERT_KeyParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format, const char *encodeType); /** * @brief Get the parse format string. * * @param format [IN] Data format * * @return Parse format string */ const char *SAL_CERT_GetParseFormatStr(HITLS_ParseFormat format); /** * @brief Copy the key. * * @param mgrCtx [IN] Certificate management struct * @param key [IN] Key * * @return Key */ HITLS_CERT_Key *SAL_CERT_KeyDup(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Key *key); /** * @brief Release the key. * * @param mgrCtx [IN] Certificate management struct * @param cert [IN] Key * * @return void */ void SAL_CERT_KeyFree(const CERT_MgrCtx *mgrCtx, HITLS_CERT_Key *key); /** * @brief Certificate store operation function * * @param config [IN] TLS link configuration * @param store [IN] Certificate store * @param cmd [IN] Operation command * @param in [IN] Input parameter * @param out [OUT] Output parameter * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_StoreCtrl(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_CtrlCmd cmd, void *in, void *out); /** * @brief Certificate operation function * * @param config [IN] TLS link configuration * @param cert [IN] Certificate * @param cmd [IN] Operation command * @param in [IN] Input parameter * @param out [OUT] Output parameter * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_X509Ctrl(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_CtrlCmd cmd, void *in, void *out); /** * @brief Key operation function * * @param config [IN] TLS link configuration * @param key [IN] Key * @param cmd [IN] Operation command * @param in [IN] Input parameter * @param out [OUT] Output parameter * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_KeyCtrl(HITLS_Config *config, HITLS_CERT_Key *key, HITLS_CERT_CtrlCmd cmd, void *in, void *out); /** * @brief Verify the certificate private key pair. * * @param config [IN] TLS link configuration * @param cert [IN] Certificate * @param key [IN] Key * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_CheckPrivateKey(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_Key *key); /** * @brief Parse CRL from data. * * @param config [IN] TLS link configuration * @param buf [IN] CRL data buffer * @param len [IN] Data length * @param type [IN] Parse type (file or buffer) * @param format [IN] Data format * * @retval HITLS_CERT_CRLList * CRL list, NULL on failure */ HITLS_CERT_CRLList *SAL_CERT_CrlParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); /** * @brief Free CRL list. * * @param crlList [IN] CRL list to be freed */ void SAL_CERT_CrlFree(HITLS_CERT_CRLList *crlList); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/include/cert_method.h
C
unknown
7,840
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CERT_MGR_H #define CERT_MGR_H #include <stdint.h> #include "hitls_type.h" #include "hitls_cert_type.h" #include "hitls_cert_reg.h" #include "hitls_cert.h" #include "tls_config.h" #include "bsl_hash.h" #ifdef __cplusplus extern "C" { #endif /* Used to transfer certificates, private keys, and certificate chains. */ typedef struct CertPairInner CERT_Pair; /** * @brief Obtain the certificate * * @param certPair [IN] Certificate resource struct * * @return Certificate */ HITLS_CERT_X509 *SAL_CERT_PairGetX509(CERT_Pair *certPair); /** * @ingroup hitls_cert_reg * @brief Obtain the encryption certificate * * @param certPair [IN] Certificate resource struct * * @return Encryption certificate */ HITLS_CERT_X509 *SAL_CERT_GetTlcpEncCert(CERT_Pair *certPair); HITLS_CERT_Chain *SAL_CERT_PairGetChain(CERT_Pair *certPair); CERT_Pair *SAL_CERT_PairDup(CERT_MgrCtx *mgrCtx, CERT_Pair *srcCertPair); /** * @brief Uninstall the certificate resource but not release the struct * * @param mgrCtx [IN] Certificate management struct * @param certPair [IN] Certificate resource struct * * @return void */ void SAL_CERT_PairClear(CERT_MgrCtx *mgrCtx, CERT_Pair *certPair); /** * @brief Release the certificate resource struct * * @param mgrCtx [IN] Certificate management struct * @param certPair [IN] Certificate resource struct. The certPair is set NULL by the invoker. * * @return void */ void SAL_CERT_PairFree(CERT_MgrCtx *mgrCtx, CERT_Pair *certPair); /** * @brief Copy certificate hash table * * @param destMgrCtx [OUT] Certificate management struct * @param srcMgrCtx [IN] Certificate management struct * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_HashDup(CERT_MgrCtx *destMgrCtx, CERT_MgrCtx *srcMgrCtx); /** * @brief Indicates whether to enable the certificate management module. * * @param void * * @retval true yes * @retval false no */ bool SAL_CERT_MgrIsEnable(void); /** * @brief Callback for obtaining a certificate * * @param NA * * @return Certificate callback */ HITLS_CERT_MgrMethod *SAL_CERT_GetMgrMethod(void); /** * @brief Create a certificate management struct * * @param void * * @return Certificate management struct */ CERT_MgrCtx *SAL_CERT_MgrCtxNew(void); /** * @brief Create a certificate management struct with provider * * @param libCtx [IN] Provider library context * @param attrName [IN] Provider attrName * * @return Certificate management struct */ CERT_MgrCtx *SAL_CERT_MgrCtxProviderNew(HITLS_Lib_Ctx *libCtx, const char *attrName); /** * @brief Copy the certificate management struct * * @param mgrCtx [IN] Certificate management struct * * @return Certificate management struct */ CERT_MgrCtx *SAL_CERT_MgrCtxDup(CERT_MgrCtx *mgrCtx); /** * @brief Release the certificate management struct * * @param mgrCtx [IN] Certificate management struct. mgrCtx is set NULL by the invoker. * * @return void */ void SAL_CERT_MgrCtxFree(CERT_MgrCtx *mgrCtx); /** * @brief Set the cert store * * @param mgrCtx [IN] Certificate management struct * @param store [IN] cert store * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetCertStore(CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store); /** * @brief Obtain the cert store * * @param mgrCtx [IN] Certificate management struct * * @return cert store */ HITLS_CERT_Store *SAL_CERT_GetCertStore(CERT_MgrCtx *mgrCtx); /** * @brief Set the chain store * * @param mgrCtx [IN] Certificate management struct * @param store [IN] chain store * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetChainStore(CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store); /** * @brief Obtain the chain store * * @param mgrCtx [IN] Certificate management struct * * @return chain store */ HITLS_CERT_Store *SAL_CERT_GetChainStore(CERT_MgrCtx *mgrCtx); /** * @brief Set the verify store * * @param mgrCtx [IN] Certificate management struct * @param store [IN] verify store * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetVerifyStore(CERT_MgrCtx *mgrCtx, HITLS_CERT_Store *store); /** * @brief Obtain the verify store * * @param mgrCtx [IN] Certificate management struct * * @return verify store */ HITLS_CERT_Store *SAL_CERT_GetVerifyStore(CERT_MgrCtx *mgrCtx); /** * @brief Add a device certificate and set it to the current. Only one certificate of each type can be added. * If the certificate is added repeatedly, the certificate will be overwritten. * * @param config [IN] Certificate management struct * @param cert [IN] Device certificate * @param isGmEncCert [IN] Indicates whether the certificate is encrypted using the TLCP. * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetCurrentCert(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isTlcpEncCert); /** * @brief Obtain the current device certificate * * @param mgrCtx [IN] Certificate management struct * * @return Device certificate */ HITLS_CERT_X509 *SAL_CERT_GetCurrentCert(CERT_MgrCtx *mgrCtx); /** * @brief Obtain the certificate of the specified type. * * @param mgrCtx [IN] Certificate management struct * @param keyType [IN] Certificate public key type * * @return Device certificate */ HITLS_CERT_X509 *SAL_CERT_GetCert(CERT_MgrCtx *mgrCtx, HITLS_CERT_KeyType keyType); /** * @brief Add a private key and set it to the current key. * Only one private key can be added for each type of certificate. * If a private key is added repeatedly, it will be overwritten. * * @param config [IN] Certificate management struct * @param key [IN] Private key * @param isGmEncCertPriKey [IN] Indicates whether the private key of the certificate encrypted * using the TLCP. * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetCurrentPrivateKey(HITLS_Config *config, HITLS_CERT_Key *key, bool isTlcpEncCertPriKey); /** * @brief Obtain the current private key * * @param mgrCtx [IN] Certificate management struct * @param isGmEncCertPriKey [IN] Indicates whether the private key of the certificate encrypted * using the TLCP. * * @return Private key */ HITLS_CERT_Key *SAL_CERT_GetCurrentPrivateKey(CERT_MgrCtx *mgrCtx, bool isTlcpEncCert); /** * @brief Obtain the private key of a specified type. * * @param mgrCtx [IN] Certificate management struct * @param keyType [IN] Private key type * * @return Private key */ HITLS_CERT_Key *SAL_CERT_GetPrivateKey(CERT_MgrCtx *mgrCtx, HITLS_CERT_KeyType keyType); int32_t SAL_CERT_AddChainCert(CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert); HITLS_CERT_Chain *SAL_CERT_GetCurrentChainCerts(CERT_MgrCtx *mgrCtx); void SAL_CERT_ClearCurrentChainCerts(CERT_MgrCtx *mgrCtx); /** * @brief Delete all certificate resources, including the device certificate, private key, and certificate chain. * * @param mgrCtx [IN] Certificate management struct * * @return void */ void SAL_CERT_ClearCertAndKey(CERT_MgrCtx *mgrCtx); int32_t SAL_CERT_AddExtraChainCert(CERT_MgrCtx *mgrCtx, HITLS_CERT_X509 *cert); HITLS_CERT_Chain *SAL_CERT_GetExtraChainCerts(CERT_MgrCtx *mgrCtx, bool isExtraChainCertsOnly); void SAL_CERT_ClearExtraChainCerts(CERT_MgrCtx *mgrCtx); /** * @brief Set or get certificate verification parameters. * * @param config [IN] TLS link configuration * @param store [IN] Certificate store * @param cmd [IN] Operation command, HITLS_CERT_CtrlCmd enum * @param in [IN] Input parameter * @param out [OUT] Output parameter * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_CtrlVerifyParams(HITLS_Config *config, HITLS_CERT_Store *store, uint32_t cmd, void *in, void *out); /** * @brief Set the default passwd callback. * * @param mgrCtx [IN] Certificate management struct * @param cb [IN] Callback function * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetDefaultPasswordCb(CERT_MgrCtx *mgrCtx, HITLS_PasswordCb cb); /** * @brief Obtain the default passwd callback. * * @param mgrCtx [IN] Certificate management struct * * @return Callback function */ HITLS_PasswordCb SAL_CERT_GetDefaultPasswordCb(CERT_MgrCtx *mgrCtx); /** * @brief Set the user data used in the default passwd callback. * * @param mgrCtx [IN] Certificate management struct * @param userdata [IN] User data * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetDefaultPasswordCbUserdata(CERT_MgrCtx *mgrCtx, void *userdata); /** * @brief Obtain the user data used in the default passwd callback. * * @param mgrCtx [IN] Certificate management struct * * @return User data */ void *SAL_CERT_GetDefaultPasswordCbUserdata(CERT_MgrCtx *mgrCtx); /** * @brief Set the verify callback function, which is used during certificate verification. * * @param mgrCtx [IN] Certificate management struct * @param cb [IN] User data * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetVerifyCb(CERT_MgrCtx *mgrCtx, HITLS_VerifyCb cb); /** * @brief Obtain the verify callback function. * * @param mgrCtx [IN] Certificate management struct * * @return Callback function */ HITLS_VerifyCb SAL_CERT_GetVerifyCb(CERT_MgrCtx *mgrCtx); /** * @brief Set the certificate callback function. * * @param mgrCtx [IN] Certificate management struct * @param certCb [IN] Certificate callback function * @param arg [IN] Parameter for the certificate callback function * * @retval HITLS_SUCCESS succeeded. */ int32_t SAL_CERT_SetCertCb(CERT_MgrCtx *mgrCtx, HITLS_CertCb certCb, void *arg); /** * @brief Free the certificate chain. * * @param chain [IN] Certificate chain */ void SAL_CERT_ChainFree(HITLS_CERT_Chain *chain); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/include/cert_mgr.h
C
unknown
10,579
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_X509_ADAPT_LOCAL_H #define HITLS_X509_ADAPT_LOCAL_H #include <stdint.h> #include "hitls_type.h" #include "hitls_cert.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #ifdef __cplusplus extern "C" { #endif HITLS_CERT_Store *HITLS_X509_Adapt_StoreNew(void); HITLS_CERT_Store *HITLS_X509_Adapt_StoreDup(HITLS_CERT_Store *store); void HITLS_X509_Adapt_StoreFree(HITLS_CERT_Store *store); int32_t HITLS_X509_Adapt_StoreCtrl(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_CtrlCmd cmd, void *input, void *output); int32_t HITLS_X509_Adapt_BuildCertChain(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_X509 *cert, HITLS_CERT_X509 **list, uint32_t *num); int32_t HITLS_X509_Adapt_VerifyCertChain(HITLS_Ctx *ctx, HITLS_CERT_Store *store, HITLS_CERT_X509 **list, uint32_t num); int32_t HITLS_X509_Adapt_CertEncode(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, uint8_t *buf, uint32_t len, uint32_t *usedLen); HITLS_CERT_X509 *HITLS_X509_Adapt_CertParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_X509 *HITLS_CERT_ProviderCertParse(HITLS_Lib_Ctx *libCtx, const char *attrName, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format); #endif HITLS_CERT_Chain *HITLS_X509_Adapt_BundleCertParse(HITLS_Lib_Ctx *libCtx, const char *attrName, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format); HITLS_CERT_X509 *HITLS_X509_Adapt_CertDup(HITLS_CERT_X509 *cert); HITLS_CERT_X509 *HITLS_X509_Adapt_CertRef(HITLS_CERT_X509 *cert); void HITLS_X509_Adapt_CertFree(HITLS_CERT_X509 *cert); int32_t HITLS_X509_Adapt_CertCtrl(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_CtrlCmd cmd, void *input, void *output); HITLS_CERT_Key *HITLS_X509_Adapt_KeyParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CERT_Key *HITLS_X509_Adapt_ProviderKeyParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format, const char *encodeType); #endif HITLS_CERT_Key *HITLS_X509_Adapt_KeyDup(HITLS_CERT_Key *key); void HITLS_X509_Adapt_KeyFree(HITLS_CERT_Key *key); int32_t HITLS_X509_Adapt_KeyCtrl(HITLS_Config *config, HITLS_CERT_Key *key, HITLS_CERT_CtrlCmd cmd, void *input, void *output); int32_t HITLS_X509_Adapt_CreateSign(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); int32_t HITLS_X509_Adapt_VerifySign(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); int32_t HITLS_X509_Adapt_Encrypt(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t HITLS_X509_Adapt_Decrypt(HITLS_Ctx *ctx, HITLS_CERT_Key *key, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t HITLS_X509_Adapt_CheckPrivateKey(const HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_Key *key); HITLS_CERT_CRLList *HITLS_X509_Adapt_CrlParse(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format); void HITLS_X509_Adapt_CrlFree(HITLS_CERT_CRLList *crlList); #ifdef __cplusplus } #endif #endif // HITLS_X509_ADAPT_LOCAL_H
2302_82127028/openHiTLS-examples_5062_4009
tls/cert/include/hitls_x509_adapt.h
C
unknown
4,067
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CONN_INIT_H #define CONN_INIT_H #include <stdint.h> #include "hitls_build.h" #include "tls.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Initialize TLS resources. * * @param ctx [IN] TLS context * * @retval HITLS_SUCCESS succeeded. * @retval HITLS_MEMALLOC_FAIL Memory application failed. * @retval HITLS_INTERNAL_EXCEPTION The input parameter is a null pointer. */ int32_t CONN_Init(TLS_Ctx *ctx); /** * @brief Release TLS resources. * * @param ctx [IN] TLS context */ void CONN_Deinit(TLS_Ctx *ctx); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/include/conn_init.h
C
unknown
1,120
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stddef.h> #include "hitls_build.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "hitls_type.h" #include "hitls_cert_type.h" #include "hitls_cert.h" #include "tls.h" int32_t HITLS_SetVerifyStore(HITLS_Ctx *ctx, HITLS_CERT_Store *store, bool isClone) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetVerifyStore(&(ctx->config.tlsConfig), store, isClone); } HITLS_CERT_Store *HITLS_GetVerifyStore(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetVerifyStore(&(ctx->config.tlsConfig)); } int32_t HITLS_SetChainStore(HITLS_Ctx *ctx, HITLS_CERT_Store *store, bool isClone) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetChainStore(&(ctx->config.tlsConfig), store, isClone); } HITLS_CERT_Store *HITLS_GetChainStore(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetChainStore(&(ctx->config.tlsConfig)); } int32_t HITLS_SetCertStore(HITLS_Ctx *ctx, HITLS_CERT_Store *store, bool isClone) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetCertStore(&(ctx->config.tlsConfig), store, isClone); } HITLS_CERT_Store *HITLS_GetCertStore(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetCertStore(&(ctx->config.tlsConfig)); } int32_t HITLS_SetDefaultPasswordCb(HITLS_Ctx *ctx, HITLS_PasswordCb cb) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetDefaultPasswordCb(&(ctx->config.tlsConfig), cb); } HITLS_PasswordCb HITLS_GetDefaultPasswordCb(HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetDefaultPasswordCb(&(ctx->config.tlsConfig)); } int32_t HITLS_SetDefaultPasswordCbUserdata(HITLS_Ctx *ctx, void *userdata) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetDefaultPasswordCbUserdata(&(ctx->config.tlsConfig), userdata); } void *HITLS_GetDefaultPasswordCbUserdata(HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetDefaultPasswordCbUserdata(&(ctx->config.tlsConfig)); } int32_t HITLS_SetCertificate(HITLS_Ctx *ctx, HITLS_CERT_X509 *cert, bool isClone) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetCertificate(&(ctx->config.tlsConfig), cert, isClone); } #ifdef HITLS_TLS_CONFIG_CERT_LOAD_FILE int32_t HITLS_LoadCertFile(HITLS_Ctx *ctx, const char *file, HITLS_ParseFormat format) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_LoadCertFile(&(ctx->config.tlsConfig), file, format); } #endif int32_t HITLS_LoadCertBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_LoadCertBuffer(&(ctx->config.tlsConfig), buf, bufLen, format); } HITLS_CERT_X509 *HITLS_GetCertificate(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetCertificate(&(ctx->config.tlsConfig)); } int32_t HITLS_SetPrivateKey(HITLS_Ctx *ctx, HITLS_CERT_Key *key, bool isClone) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetPrivateKey(&(ctx->config.tlsConfig), key, isClone); } #ifdef HITLS_TLS_CONFIG_CERT_LOAD_FILE int32_t HITLS_ProviderLoadKeyFile(HITLS_Ctx *ctx, const char *file, const char *format, const char *type) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_ProviderLoadKeyFile(&(ctx->config.tlsConfig), file, format, type); } int32_t HITLS_LoadKeyFile(HITLS_Ctx *ctx, const char *file, HITLS_ParseFormat format) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_LoadKeyFile(&(ctx->config.tlsConfig), file, format); } #endif /* HITLS_TLS_CONFIG_CERT_LOAD_FILE */ int32_t HITLS_ProviderLoadKeyBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, const char *format, const char *type) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_ProviderLoadKeyBuffer(&(ctx->config.tlsConfig), buf, bufLen, format, type); } int32_t HITLS_LoadKeyBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_LoadKeyBuffer(&(ctx->config.tlsConfig), buf, bufLen, format); } HITLS_CERT_Key *HITLS_GetPrivateKey(HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetPrivateKey(&(ctx->config.tlsConfig)); } int32_t HITLS_CheckPrivateKey(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_CheckPrivateKey(&(ctx->config.tlsConfig)); } int32_t HITLS_RemoveCertAndKey(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_RemoveCertAndKey(&(ctx->config.tlsConfig)); } int32_t HITLS_SetVerifyCb(HITLS_Ctx *ctx, HITLS_VerifyCb callback) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetVerifyCb(&(ctx->config.tlsConfig), callback); } HITLS_VerifyCb HITLS_GetVerifyCb(HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetVerifyCb(&(ctx->config.tlsConfig)); } int32_t HITLS_LoadCrlFile(HITLS_Ctx *ctx, const char *file, HITLS_ParseFormat format) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_LoadCrlFile(&(ctx->config.tlsConfig), file, format); } int32_t HITLS_LoadCrlBuffer(HITLS_Ctx *ctx, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_LoadCrlBuffer(&(ctx->config.tlsConfig), buf, bufLen, format); } int32_t HITLS_ClearVerifyCrls(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_ClearVerifyCrls(&(ctx->config.tlsConfig)); } #ifdef HITLS_TLS_CONFIG_CERT_LOAD_FILE int32_t HITLS_UseCertificateChainFile(HITLS_Ctx *ctx, const char *file) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_UseCertificateChainFile(&(ctx->config.tlsConfig), file); } #endif /* HITLS_TLS_CONFIG_CERT_LOAD_FILE */
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_cert.c
C
unknown
6,936
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "bsl_list.h" #include "tls.h" #include "hitls.h" #include "hitls_error.h" #include "hitls_type.h" #ifdef HITLS_TLS_FEATURE_PSK #include "hitls_psk.h" #endif #ifdef HITLS_TLS_FEATURE_ALPN #include "hitls_alpn.h" #endif #include "hs.h" #include "alert.h" #include "app.h" #ifdef HITLS_TLS_FEATURE_SESSION #include "session.h" #endif #ifdef HITLS_TLS_FEATURE_INDICATOR #include "indicator.h" #endif #include "rec.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "hs_ctx.h" #include "conn_common.h" static const char *GetStateString(uint32_t state) { /* * Unknown status */ if (state >= CM_STATE_END) { return "Unknown"; } static const char *stateMachineStr[CM_STATE_END] = { [CM_STATE_IDLE] = "Idle", [CM_STATE_RENEGOTIATION] = "SecRenego", [CM_STATE_HANDSHAKING] = "Handshaking", [CM_STATE_TRANSPORTING] = "Transporting", [CM_STATE_ALERTING] = "Alerting", [CM_STATE_ALERTED] = "Alerted", [CM_STATE_CLOSED] = "Closed", }; /* Current status */ return stateMachineStr[state]; } void ChangeConnState(HITLS_Ctx *ctx, CM_State state) { if (GetConnState(ctx) == state) { return; } ctx->preState = ctx->state; ctx->state = state; BSL_LOG_BINLOG_VARLEN(BINLOG_ID15839, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "state [%s]", GetStateString(ctx->preState)); BSL_LOG_BINLOG_VARLEN(BINLOG_ID15840, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "change to [%s]", GetStateString(state)); return; } int32_t CommonEventInAlertingState(HITLS_Ctx *ctx) { /* The alerting state indicates that an alert message is being sent over the current link. In this case, the alert * message should firstly be sent and then the link status will be updated */ ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(ctx, &alertInfo); if (alertInfo.level > ALERT_LEVEL_FATAL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16458, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "level error", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } int32_t ret = ALERT_Flush(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16459, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ALERT_Flush fail", 0, 0, 0, 0); /* If the alert fails to be sent, return error code to user */ return ret; } #ifdef HITLS_TLS_FEATURE_INDICATOR uint8_t data[2] = {alertInfo.level, alertInfo.description}; INDICATOR_MessageIndicate(1, HS_GetVersion(ctx), REC_TYPE_ALERT, data, sizeof(data) / sizeof(uint8_t), ctx, ctx->config.tlsConfig.msgArg); INDICATOR_StatusIndicate(ctx, INDICATE_EVENT_WRITE_ALERT, (int32_t)(((uint32_t)(alertInfo.level) << INDICATOR_ALERT_LEVEL_OFFSET) | (uint32_t)(alertInfo.description))); #endif /* If a fatal alert is sent, the link must be disconnected */ if (alertInfo.level == ALERT_LEVEL_FATAL) { #ifdef HITLS_TLS_FEATURE_SESSION SESS_Disable(ctx->session); #endif ChangeConnState(ctx, CM_STATE_ALERTED); return HITLS_SUCCESS; } /* If the close_notify message is sent, the link must be disconnected */ if (alertInfo.description == ALERT_CLOSE_NOTIFY) { if (ctx->userShutDown) { ChangeConnState(ctx, CM_STATE_CLOSED); } else { ChangeConnState(ctx, CM_STATE_ALERTED); } ctx->shutdownState |= HITLS_SENT_SHUTDOWN; /* If the previous state was not in the transporting state, the connection should be closed directly, and * reading and writing are not allowed. */ if (ctx->preState != CM_STATE_TRANSPORTING) { ctx->shutdownState |= HITLS_RECEIVED_SHUTDOWN; } return HITLS_SUCCESS; } /* Other warning alerts will not terminate the connection and the status will be restored to the previous status */ ctx->state = ctx->preState; ALERT_CleanInfo(ctx); return HITLS_SUCCESS; } static int32_t AlertRecvProcess(HITLS_Ctx *ctx, const ALERT_Info *alertInfo) { #ifdef HITLS_TLS_FEATURE_INDICATOR uint8_t data[2] = {alertInfo->level, alertInfo->description}; INDICATOR_MessageIndicate(0, HS_GetVersion(ctx), REC_TYPE_ALERT, data, sizeof(data) / sizeof(uint8_t), ctx, ctx->config.tlsConfig.msgArg); INDICATOR_StatusIndicate(ctx, INDICATE_EVENT_READ_ALERT, (int32_t)(((uint32_t)(alertInfo->level) << INDICATOR_ALERT_LEVEL_OFFSET) | (uint32_t)(alertInfo->description))); #endif /* If a fatal alert is received, the link must be disconnected */ if (alertInfo->level == ALERT_LEVEL_FATAL) { #ifdef HITLS_TLS_FEATURE_SESSION SESS_Disable(ctx->session); #endif ChangeConnState(ctx, CM_STATE_ALERTED); ctx->shutdownState |= HITLS_RECEIVED_SHUTDOWN; return HITLS_SUCCESS; } /* If a warning alert is received, the connection must be terminated if the alert is close_notify. Otherwise, the * alert will not be processed */ ALERT_CleanInfo(ctx); if (alertInfo->description != ALERT_CLOSE_NOTIFY) { /* Other warning alerts will not be processed */ return HITLS_SUCCESS; } ctx->shutdownState |= HITLS_RECEIVED_SHUTDOWN; /* In quiet disconnection mode, close_notify does not need to be sent */ if (ctx->config.tlsConfig.isQuietShutdown) { ctx->shutdownState |= HITLS_SENT_SHUTDOWN; ChangeConnState(ctx, CM_STATE_ALERTED); return HITLS_SUCCESS; } if ((ctx->shutdownState & HITLS_SENT_SHUTDOWN) == 0) { if (GetConnState(ctx) != CM_STATE_TRANSPORTING) { /* If the close_notify message is received, the close_notify message must be sent to the peer */ ALERT_Send(ctx, ALERT_LEVEL_WARNING, ALERT_CLOSE_NOTIFY); ChangeConnState(ctx, CM_STATE_ALERTING); int32_t ret = ALERT_Flush(ctx); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16460, "ALERT_Flush fail"); } ctx->shutdownState |= HITLS_SENT_SHUTDOWN; } else { ChangeConnState(ctx, CM_STATE_CLOSED); } } if (ctx->state != CM_STATE_CLOSED) { ChangeConnState(ctx, CM_STATE_ALERTED); } return HITLS_CM_LINK_CLOSED; } int32_t AlertEventProcess(HITLS_Ctx *ctx) { ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(ctx, &alertInfo); /* An alert message is received. */ if (alertInfo.flag == ALERT_FLAG_RECV) { return AlertRecvProcess(ctx, &alertInfo); } /* An alert message needs to be sent */ if (alertInfo.flag == ALERT_FLAG_SEND) { ChangeConnState(ctx, CM_STATE_ALERTING); return CommonEventInAlertingState(ctx); } return HITLS_SUCCESS; } int32_t CommonEventInHandshakingState(HITLS_Ctx *ctx) { int32_t ret; int32_t alertRet; do { ret = HS_DoHandshake(ctx); if (ret == HITLS_SUCCESS) { /* The handshake has completed */ break; } if (ret == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG && REC_GetUnexpectedMsgType(ctx) == REC_TYPE_APP) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16489, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "The app message is received in the handshake state", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } if (!ALERT_GetFlag(ctx)) { /* The handshake fails, but no alert is received. Return the error code to the user */ return ret; } if (ALERT_HaveExceeded(ctx, MAX_ALERT_COUNT)) { /* If there are multiple consecutive alerts, the link is abnormal and needs to be terminated. */ ALERT_Send(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); alertRet = AlertEventProcess(ctx); return (alertRet == HITLS_SUCCESS) ? ret : alertRet; } alertRet = AlertEventProcess(ctx); if (alertRet != HITLS_SUCCESS) { /* If the alert message fails to be sent, return the error code to the user */ return alertRet; } /* If fatal alert or close_notify has been processed, the handshake must be terminated */ if (ctx->state == CM_STATE_ALERTED) { return ret; } } while (ret != HITLS_SUCCESS); // If HS_DoHandshake returns success, the connection has been established. ChangeConnState(ctx, CM_STATE_TRANSPORTING); HS_DeInit(ctx); return HITLS_SUCCESS; } const HITLS_Config *HITLS_GetConfig(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return &(ctx->config.tlsConfig); } HITLS_Config *HITLS_GetGlobalConfig(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return ctx->globalConfig; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t HITLS_ClearTLS13CipherSuites(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_ClearTLS13CipherSuites(&(ctx->config.tlsConfig)); } #endif int32_t HITLS_SetCipherSuites(HITLS_Ctx *ctx, const uint16_t *cipherSuites, uint32_t cipherSuitesSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetCipherSuites(&(ctx->config.tlsConfig), cipherSuites, cipherSuitesSize); } #ifdef HITLS_TLS_FEATURE_ALPN int32_t HITLS_SetAlpnProtos(HITLS_Ctx *ctx, const uint8_t *protos, uint32_t protosLen) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetAlpnProtos(&(ctx->config.tlsConfig), protos, protosLen); } #endif #ifdef HITLS_TLS_FEATURE_PSK int32_t HITLS_SetPskClientCallback(HITLS_Ctx *ctx, HITLS_PskClientCb cb) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetPskClientCallback(&(ctx->config.tlsConfig), cb); } int32_t HITLS_SetPskServerCallback(HITLS_Ctx *ctx, HITLS_PskServerCb cb) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetPskServerCallback(&(ctx->config.tlsConfig), cb); } #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t HITLS_SetPskIdentityHint(HITLS_Ctx *ctx, const uint8_t *identityHint, uint32_t identityHintLen) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetPskIdentityHint(&(ctx->config.tlsConfig), identityHint, identityHintLen); } #endif #endif #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION const HITLS_Cipher *HITLS_GetCurrentCipher(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return &(ctx->negotiatedInfo.cipherSuiteInfo); } #endif int32_t HITLS_IsClient(const HITLS_Ctx *ctx, bool *isClient) { if (ctx == NULL || isClient == NULL) { return HITLS_NULL_INPUT; } *isClient = ctx->isClient; return HITLS_SUCCESS; } #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_GetHsRandom(const HITLS_Ctx *ctx, uint8_t *out, uint32_t *outlen, bool isClient) { if (ctx == NULL || outlen == NULL) { return HITLS_NULL_INPUT; } if (*outlen == 0) { *outlen = RANDOM_SIZE; return HITLS_SUCCESS; } uint32_t resLen = *outlen; if (resLen > RANDOM_SIZE) { resLen = RANDOM_SIZE; } if (out == NULL) { *outlen = resLen; return HITLS_SUCCESS; } if (isClient) { (void)memcpy_s(out, resLen, ctx->negotiatedInfo.clientRandom, resLen); } else { (void)memcpy_s(out, resLen, ctx->negotiatedInfo.serverRandom, resLen); } *outlen = resLen; return HITLS_SUCCESS; } /* * If current endpoint is a server and the server preference is supported, the local server group array is preferred. * If current endpoint is a server and the client preference is supported, the peer (client)group array is preferred */ static uint16_t FindPreference(const HITLS_Ctx *ctx, int32_t nmatch, bool *haveFound) { uint16_t ans = 0; uint32_t preferGroupSize = 0; uint32_t secondPreferGroupSize = 0; uint16_t *preferGroups = NULL; uint16_t *secondPreferGroups = NULL; uint32_t peerGroupSize = ctx->peerInfo.groupsSize; uint32_t localGroupSize = ctx->config.tlsConfig.groupsSize; uint16_t *peerGroups = ctx->peerInfo.groups; uint16_t *localGroups = ctx->config.tlsConfig.groups; bool chooseServerPre = ctx->config.tlsConfig.isSupportServerPreference; uint16_t intersectionCnt = 0; preferGroupSize = (chooseServerPre == true) ? localGroupSize : peerGroupSize; secondPreferGroupSize = (chooseServerPre == true) ? peerGroupSize : localGroupSize; preferGroups = (chooseServerPre == true) ? localGroups : peerGroups; secondPreferGroups = (chooseServerPre == true) ? peerGroups : localGroups; for (uint32_t i = 0; i < preferGroupSize; i++) { for (uint32_t j = 0; j < secondPreferGroupSize; j++) { if (preferGroups[i] == secondPreferGroups[j]) { intersectionCnt++; // Currently, the preferred nmatch is already matched bool isMatch = (intersectionCnt == nmatch); *haveFound = (isMatch ? true : (*haveFound)); ans = (isMatch ? preferGroups[i] : ans); // Jump out of the inner village and change break; } } if (*haveFound) { // Exit a loop break; } } if (nmatch == GET_GROUPS_CNT) { return (uint16_t)intersectionCnt; } return ans; } /* * nmatch Value range: - 1 or a positive integer * This function can be invoked only after negotiation and can be invoked only by the server. * When nmatch is a positive integer, check the intersection of groups on the client and server, and return the nmatch * group in the intersection by groupId. If the value of nmatch is - 1, the number of intersection groups on the client * and server is returned based on groupId. */ int32_t HITLS_GetSharedGroup(const HITLS_Ctx *ctx, int32_t nmatch, uint16_t *groupId) { bool haveFound = false; if (ctx == NULL || groupId == NULL) { return HITLS_NULL_INPUT; } *groupId = 0; // Check the value range of nmatch and whether the interface is invoked by the server. The client cannot invoke the // interface because the client cannot sense the peerInfo. if (nmatch < GET_GROUPS_CNT || nmatch == 0 || ctx->isClient) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16464, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "invalid input", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } *groupId = FindPreference(ctx, nmatch, &haveFound); if (nmatch == GET_GROUPS_CNT) { // The value of *groupId is the number of intersections return HITLS_SUCCESS; } else if (haveFound == false) { // If nmatch is not equal to GET_GROUPS_CNT and haveFound is false BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16465, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input err", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_CONNECTION_INFO_NEGOTIATION */ #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_GetPeerFinishVerifyData(const HITLS_Ctx *ctx, void *buf, uint32_t bufLen, uint32_t *dataLen) { uint32_t verifyDataSize, bufSize; const uint8_t *verifyData = NULL; if (ctx == NULL || buf == NULL || bufLen == 0 || dataLen == NULL) { return HITLS_NULL_INPUT; } if (ctx->isClient) { verifyDataSize = ctx->negotiatedInfo.serverVerifyDataSize; verifyData = ctx->negotiatedInfo.serverVerifyData; } else { verifyDataSize = ctx->negotiatedInfo.clientVerifyDataSize; verifyData = ctx->negotiatedInfo.clientVerifyData; } if (bufLen > verifyDataSize) { bufSize = verifyDataSize; } else { bufSize = bufLen; } (void)memcpy_s(buf, bufLen, verifyData, bufSize); *dataLen = verifyDataSize; return HITLS_SUCCESS; } int32_t HITLS_GetFinishVerifyData(const HITLS_Ctx *ctx, void *buf, uint32_t bufLen, uint32_t *dataLen) { uint32_t verifyDataSize, bufSize; const uint8_t *verifyData = NULL; if (ctx == NULL || buf == NULL || bufLen == 0 || dataLen == NULL) { return HITLS_NULL_INPUT; } if (ctx->isClient) { verifyDataSize = ctx->negotiatedInfo.clientVerifyDataSize; verifyData = ctx->negotiatedInfo.clientVerifyData; } else { verifyDataSize = ctx->negotiatedInfo.serverVerifyDataSize; verifyData = ctx->negotiatedInfo.serverVerifyData; } if (bufLen > verifyDataSize) { bufSize = verifyDataSize; } else { bufSize = bufLen; } (void)memcpy_s(buf, bufLen, verifyData, bufSize); *dataLen = verifyDataSize; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ #ifdef HITLS_TLS_PROTO_ALL int32_t HITLS_GetVersionSupport(const HITLS_Ctx *ctx, uint32_t *version) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetVersionSupport(&(ctx->config.tlsConfig), version); } int32_t HITLS_SetVersionSupport(HITLS_Ctx *ctx, uint32_t version) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetVersionSupport(&(ctx->config.tlsConfig), version); } #endif #ifdef HITLS_TLS_SUITE_KX_RSA int32_t HITLS_SetNeedCheckPmsVersion(HITLS_Ctx *ctx, bool needCheck) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetNeedCheckPmsVersion(&(ctx->config.tlsConfig), needCheck); } #endif #ifdef HITLS_TLS_FEATURE_RENEGOTIATION static bool HS_IsAppDataAllowed(TLS_Ctx *ctx) { uint32_t hsState = HS_GetState(ctx); if (ctx->isClient) { if (hsState == TRY_RECV_SERVER_HELLO) { return true; } } else { if (hsState == TRY_RECV_CLIENT_HELLO) { return true; } } return false; } void InnerRenegotiationProcess(HITLS_Ctx *ctx) { ALERT_Info alertInfo = { 0 }; ALERT_GetInfo(ctx, &alertInfo); if ((alertInfo.level == ALERT_LEVEL_WARNING) && (alertInfo.description == ALERT_NO_RENEGOTIATION)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16234, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Receive no renegotiation alert during renegotiation process", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_HANDSHAKE_FAILURE); } } int32_t CommonEventInRenegotiationState(HITLS_Ctx *ctx) { int32_t ret; do { ret = HS_DoHandshake(ctx); if (ret == HITLS_SUCCESS) { /* The handshake has completed */ break; } if (ret == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG && REC_GetUnexpectedMsgType(ctx) == REC_TYPE_APP) { if (ctx->allowAppOut && HS_IsAppDataAllowed(ctx)) { return ret; } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17106, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "The app message is received in the handshake state", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } if (!ALERT_GetFlag(ctx)) { /* The handshake fails, but no alert is displayed. The system returns a message * to the user for processing */ return ret; } InnerRenegotiationProcess(ctx); if (ALERT_HaveExceeded(ctx, MAX_ALERT_COUNT)) { /* If multiple consecutive alerts exist, the link is abnormal and needs to be terminated */ ALERT_Send(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } int32_t alertRet = AlertEventProcess(ctx); if (alertRet != HITLS_SUCCESS) { if (alertRet != HITLS_CM_LINK_CLOSED) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16466, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "AlertEventProcess fail", 0, 0, 0, 0); } /* If the alert fails to be sent, the system sends a message to the user for processing */ return alertRet; } /* If fatal alert or close_notify has been processed, the handshake must be terminated. */ if (ctx->state == CM_STATE_ALERTED) { return ret; } } while (ret != HITLS_SUCCESS); // If the HS_DoHandshake message is returned successfully, the link has been terminated. ChangeConnState(ctx, CM_STATE_TRANSPORTING); HS_DeInit(ctx); // Prevent the renegotiation status from being changed after the Hello Request message is sent. if (ctx->negotiatedInfo.isRenegotiation) { ctx->userRenego = false; ctx->negotiatedInfo.isRenegotiation = false; /* Disabling renegotiation */ BSL_LOG_BINLOG_FIXLEN( BINLOG_ID15952, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "renegotiate completed.", 0, 0, 0, 0); } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ #if defined(HITLS_TLS_FEATURE_PSK) && defined(HITLS_TLS_PROTO_TLS13) int32_t HITLS_SetPskFindSessionCallback(HITLS_Ctx *ctx, HITLS_PskFindSessionCb cb) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetPskFindSessionCallback(&(ctx->config.tlsConfig), cb); } int32_t HITLS_SetPskUseSessionCallback(HITLS_Ctx *ctx, HITLS_PskUseSessionCb cb) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetPskUseSessionCallback(&(ctx->config.tlsConfig), cb); } #endif #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_GetNegotiateGroup(const HITLS_Ctx *ctx, uint16_t *group) { if (ctx == NULL || group == NULL) { return HITLS_NULL_INPUT; } *group = ctx->negotiatedInfo.negotiatedGroup; return HITLS_SUCCESS; } #endif int32_t HITLS_GetOutPendingSize(const HITLS_Ctx *ctx, uint32_t *size) { if (ctx == NULL || size == NULL || ctx->recCtx == NULL) { return HITLS_NULL_INPUT; } *size = REC_GetOutBufPendingSize(ctx); return HITLS_SUCCESS; } int32_t HITLS_Flush(HITLS_Ctx *ctx) { if (ctx == NULL || ctx->recCtx == NULL) { return HITLS_NULL_INPUT; } #ifdef HITLS_TLS_PROTO_TLS return REC_OutBufFlush(ctx); #else return HITLS_SUCCESS; #endif }
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_common.c
C
unknown
23,002
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CONN_COMMON_H #define CONN_COMMON_H #include <stdint.h> #include "hitls_build.h" #include "tls.h" #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define MAX_ALERT_COUNT 5u #define GET_GROUPS_CNT (-1) typedef int32_t (*ManageEventProcess)(HITLS_Ctx *ctx); typedef int32_t (*WriteEventProcess)(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen); typedef int32_t (*ReadEventProcess)(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen); static inline CM_State GetConnState(const HITLS_Ctx *ctx) { return ctx->state; } #ifdef HITLS_TLS_FEATURE_PHA int32_t CommonCheckPostHandshakeAuth(TLS_Ctx *ctx); #endif /** * @ingroup hitls * @brief General processing of all events in alerting state */ int32_t CommonEventInAlertingState(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief Processe of common events in hanshaking state, attempt to establish a connection */ int32_t CommonEventInHandshakingState(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief If the local end generates an Alert message when sending or receiving messages or processing handshake * messages, or receives an Alert message from the peer end, the AlertEventProcess needs to be invoked to * process the Alert status. */ int32_t AlertEventProcess(HITLS_Ctx *ctx); void ChangeConnState(HITLS_Ctx *ctx, CM_State state); #ifdef HITLS_TLS_FEATURE_RENEGOTIATION /** * @ingroup hitls * @brief In the renegotiation state, process the renegotiation event and attempt to establish a connection * * @param ctx [IN] TLS connection handle * * @retval HITLS_SUCCESS succeeded * @retval For other error codes, see hitls_error.h */ int32_t CommonEventInRenegotiationState(HITLS_Ctx *ctx); /** * @ingroup hitls * @brief In the renegotiation state, process no_renegotiation alert. * Send a handshake_failure alert if no_renegotiation alert is received. * * @param ctx [IN] TLS connection handle * */ void InnerRenegotiationProcess(HITLS_Ctx *ctx); #endif #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_common.h
C
unknown
2,625
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_err_internal.h" #include "tls_binlog_id.h" #include "bsl_sal.h" #include "bsl_errno.h" #include "bsl_list.h" #include "hitls_error.h" #include "hitls_type.h" #include "hitls_config.h" #include "hitls_cert_type.h" #include "hitls.h" #include "tls.h" #include "tls_config.h" #include "cert.h" #ifdef HITLS_TLS_FEATURE_SESSION #include "session.h" #include "session_mgr.h" #endif #include "bsl_uio.h" #include "config.h" #include "config_check.h" #include "conn_common.h" #include "conn_init.h" #include "crypt.h" #include "cipher_suite.h" #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION static int32_t PeerInfoInit(HITLS_Ctx *ctx) { /* The peerInfo.caList is used to adapt to the OpenSSL behavior. When creating the SSL_CTX object, OpenSSL * initializes the member so that the member is not null */ ctx->peerInfo.caList = BSL_LIST_New(sizeof(HITLS_TrustedCANode *)); if (ctx->peerInfo.caList == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16468, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "LIST_New fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } #endif /** * @ingroup hitls * @brief Create a TLS object and deep Copy the HITLS_Config to the HITLS_Ctx. * @attention After the creation is successful, the HITLS_Config can be released. * @param config [IN] config Context * @return HITLS_Ctx Pointer. If the operation fails, null is returned. */ HITLS_Ctx *HITLS_New(HITLS_Config *config) { if (config == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16469, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "config null", 0, 0, 0, 0); return NULL; } HITLS_Ctx *newCtx = (HITLS_Ctx *)BSL_SAL_Calloc(1u, sizeof(HITLS_Ctx)); if (newCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16470, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } int32_t ret = CheckConfig(config); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16471, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CheckConfig fail, ret %d", ret, 0, 0, 0); BSL_SAL_FREE(newCtx); return NULL; } ret = DumpConfig(newCtx, config); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16472, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "DumpConfig fail, ret %d", ret, 0, 0, 0); BSL_SAL_FREE(newCtx); return NULL; } (void)HITLS_CFG_UpRef(config); newCtx->globalConfig = config; #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION ret = PeerInfoInit(newCtx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16473, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PeerInfoInit fail, ret %d", ret, 0, 0, 0); HITLS_Free(newCtx); return NULL; } #endif ChangeConnState(newCtx, CM_STATE_IDLE); return newCtx; } static void CaListNodeDestroy(void *data) { HITLS_TrustedCANode *tmpData = (HITLS_TrustedCANode *)data; BSL_SAL_FREE(tmpData->data); BSL_SAL_FREE(tmpData); return; } static void CleanPeerInfo(PeerInfo *peerInfo) { BSL_SAL_FREE(peerInfo->groups); BSL_SAL_FREE(peerInfo->cipherSuites); BSL_LIST_FREE(peerInfo->caList, (BSL_LIST_PFUNC_FREE)CaListNodeDestroy); BSL_SAL_FREE(peerInfo->signatureAlgorithms); } #if defined(HITLS_TLS_EXTENSION_COOKIE) || defined(HITLS_TLS_FEATURE_ALPN) static void CleanNegotiatedInfo(TLS_NegotiatedInfo *negotiatedInfo) { #ifdef HITLS_TLS_EXTENSION_COOKIE BSL_SAL_FREE(negotiatedInfo->cookie); #endif #ifdef HITLS_TLS_FEATURE_ALPN BSL_SAL_FREE(negotiatedInfo->alpnSelected); #endif return; } #endif /** * @ingroup hitls * @brief Release the TLS connection. * @param ctx [IN] TLS connection handle. * @return void */ void HITLS_Free(HITLS_Ctx *ctx) { if (ctx == NULL) { return; } #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif CONN_Deinit(ctx); BSL_UIO_Free(ctx->uio); #ifdef HITLS_TLS_FEATURE_FLIGHT BSL_UIO_Free(ctx->rUio); ctx->rUio = NULL; #endif ctx->uio = NULL; #ifdef HITLS_TLS_FEATURE_SESSION /* Release certificate resources before releasing the config file. Otherwise, memory leakage occurs */ HITLS_SESS_Free(ctx->session); #endif CFG_CleanConfig(&ctx->config.tlsConfig); HITLS_CFG_FreeConfig(ctx->globalConfig); CleanPeerInfo(&(ctx->peerInfo)); #if defined(HITLS_TLS_EXTENSION_COOKIE) || defined(HITLS_TLS_FEATURE_ALPN) CleanNegotiatedInfo(&ctx->negotiatedInfo); #endif #ifdef HITLS_TLS_FEATURE_PHA SAL_CRYPT_DigestFree(ctx->phaHash); ctx->phaHash = NULL; SAL_CRYPT_DigestFree(ctx->phaCurHash); ctx->phaCurHash = NULL; ctx->phaState = PHA_NONE; BSL_SAL_FREE(ctx->certificateReqCtx); ctx->certificateReqCtxSize = 0; #endif BSL_SAL_FREE(ctx); return; } #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t HITLS_SetReadUio(HITLS_Ctx *ctx, BSL_UIO *uio) { if ((ctx == NULL) || (uio == NULL)) { return HITLS_NULL_INPUT; } int32_t ret = BSL_UIO_UpRef(uio); if (ret != BSL_SUCCESS) { return HITLS_UIO_FAIL; } if (ctx->rUio != NULL) { /* A message is displayed, warning the user that the UIO is set repeatedly */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15662, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "Warning: Repeated uio setting.", 0, 0, 0, 0); /* Release the original UIO */ BSL_UIO_Free(ctx->rUio); } ctx->rUio = uio; return HITLS_SUCCESS; } #endif static void ConfigPmtu(HITLS_Ctx *ctx, BSL_UIO *uio) { (void)ctx; (void)uio; #ifdef HITLS_TLS_PROTO_DTLS12 /* The PMTU needs to be set for DTLS. If the PMTU is not set, use the default value */ if ((ctx->config.pmtu == 0) && IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { if (BSL_UIO_GetUioChainTransportType(uio, BSL_UIO_UDP)) { uint8_t overhead = 0; (void)BSL_UIO_Ctrl(ctx->uio, BSL_UIO_UDP_GET_MTU_OVERHEAD, sizeof(uint8_t), &overhead); ctx->config.pmtu = DTLS_DEFAULT_PMTU - (uint16_t)overhead; } else { ctx->config.pmtu = DTLS_SCTP_PMTU; } } #endif } /** * @ingroup hitls * @brief Set the UIO for the HiTLS context. * @attention This function must be called before HITLS_Connect and HITLS_Accept and released after HITLS_Free. If this * function has been called, you must call BSL_UIO_Free to release the UIO. * @param ctx [OUT] TLS connection handle. * @param uio [IN] UIO object * @return HITLS_SUCCESS succeeded * Other Error Codes, see hitls_error.h */ int32_t HITLS_SetUio(HITLS_Ctx *ctx, BSL_UIO *uio) { if ((ctx == NULL) || (uio == NULL)) { return HITLS_NULL_INPUT; } /* The UIO count increases by 1, and the reference counting is performed for the write UIO */ int32_t ret = BSL_UIO_UpRef(uio); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16474, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "UIO_UpRef fail, ret %d", ret, 0, 0, 0); return HITLS_UIO_FAIL; } #ifdef HITLS_TLS_FEATURE_FLIGHT /* The UIO count increases by 1, and the reference counting is performed for reading the UIO */ ret = BSL_UIO_UpRef(uio); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16475, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "UIO_UpRef fail, ret %d", ret, 0, 0, 0); BSL_UIO_Free(uio); // free Drop the one on the top. return HITLS_UIO_FAIL; } #endif /* The original write uio is not empty */ if (ctx->uio != NULL) { /* A message is displayed, warning the user that the UIO is set repeatedly. */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15960, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "Warning: Repeated uio setting.", 0, 0, 0, 0); /* Release the original write UIO */ if (ctx->bUio != NULL) { ctx->uio = BSL_UIO_PopCurrent(ctx->uio); } BSL_UIO_FreeChain(ctx->uio); } ctx->uio = uio; #ifdef HITLS_TLS_FEATURE_FLIGHT if (ctx->bUio != NULL) { ret = BSL_UIO_Append(ctx->bUio, ctx->uio); if (ret != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16476, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "UIO_Append fail, ret %d", ret, 0, 0, 0); BSL_UIO_Free(uio); // free Drop the one on the top. return HITLS_UIO_FAIL; } ctx->uio = ctx->bUio; } /* The original read UIO is not empty */ if (ctx->rUio != NULL) { /* A message is displayed, warning the user that the UIO is set repeatedly */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15253, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "Warning: Repeated uio setting.", 0, 0, 0, 0); /* Release the original read UIO */ BSL_UIO_Free(ctx->rUio); } ctx->rUio = uio; #endif ConfigPmtu(ctx, uio); return HITLS_SUCCESS; } BSL_UIO *HITLS_GetUio(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } #ifdef HITLS_TLS_FEATURE_FLIGHT /* If |bUio| is active, the true caller-configured uio is its |next_uio|. */ if (ctx->config.tlsConfig.isFlightTransmitEnable == true && ctx->bUio != NULL) { return BSL_UIO_Next(ctx->bUio); } #endif return ctx->uio; } BSL_UIO *HITLS_GetReadUio(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return ctx->rUio; } /** * @ingroup hitls * @brief Obtain user data from the HiTLS context. Generally, this interface is invoked during the callback registered * with the HiTLS. * @attention must be invoked before HITLS_Connect and HITLS_Accept. The life cycle of the user identifier must be * longer than the life cycle of the TLS object. * @param ctx [OUT] TLS connection handle. * @param userData [IN] User identifier. * @retval HITLS_SUCCESS succeeded. * @retval HITLS_NULL_INPUT The input parameter TLS object is a null pointer. */ void *HITLS_GetUserData(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return ctx->config.userData; } /** * @ingroup hitls * @brief User data is stored in the HiTLS context and can be obtained from the callback registered with the HiTLS. * @attention must be invoked before HITLS_Connect and HITLS_Accept. The life cycle of the user identifier must be * longer than the life cycle of the TLS object. If the user data needs to be cleared, the * HITLS_SetUserData(ctx, NULL) interface can be invoked directly. The Clean interface is not provided separately. * @param ctx [OUT] TLS connection handle. * @param userData [IN] User identifier. * @retval HITLS_SUCCESS succeeded. * @retval HITLS_NULL_INPUT The input parameter TLS object is a null pointer. */ int32_t HITLS_SetUserData(HITLS_Ctx *ctx, void *userData) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->config.userData = userData; return HITLS_SUCCESS; } int32_t HITLS_SetErrorCode(HITLS_Ctx *ctx, int32_t errorCode) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->errorCode = errorCode; return HITLS_SUCCESS; } int32_t HITLS_GetErrorCode(const HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return ctx->errorCode; } #ifdef HITLS_TLS_FEATURE_ALPN int32_t HITLS_GetSelectedAlpnProto(HITLS_Ctx *ctx, uint8_t **proto, uint32_t *protoLen) { if (ctx == NULL || proto == NULL || protoLen == NULL) { return HITLS_NULL_INPUT; } if (ctx->negotiatedInfo.alpnSelected == NULL) { return HITLS_NULL_INPUT; } *proto = ctx->negotiatedInfo.alpnSelected; *protoLen = ctx->negotiatedInfo.alpnSelectedSize; return HITLS_SUCCESS; } #endif int32_t HITLS_IsServer(const HITLS_Ctx *ctx, uint8_t *isServer) { if (ctx == NULL || isServer == NULL) { return HITLS_NULL_INPUT; } *isServer = 0; if (ctx->isClient == false) { *isServer = 1; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SESSION /* Configure the handle for the session information about the HITLS link */ int32_t HITLS_SetSession(HITLS_Ctx *ctx, HITLS_Session *session) { if (ctx == NULL) { return HITLS_NULL_INPUT; } /* The client and server are specified only in hitls connect/accept. Therefore, the client cannot be specified here */ HITLS_SESS_Free(ctx->session); /* Ignore whether the HITLS_SESS_Dup return is NULL or non-NULL */ ctx->session = HITLS_SESS_Dup(session); return HITLS_SUCCESS; } /* Obtain the session information handle and directly obtain the pointer */ HITLS_Session *HITLS_GetSession(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return ctx->session; } /* Obtain the handle of the copied session information */ HITLS_Session *HITLS_GetDupSession(HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_SESS_Dup(ctx->session); } #endif #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_GetPeerSignatureType(const HITLS_Ctx *ctx, HITLS_SignAlgo *sigType) { HITLS_SignAlgo signAlg = HITLS_SIGN_BUTT; HITLS_HashAlgo hashAlg = HITLS_HASH_BUTT; if (ctx == NULL || sigType == NULL) { return HITLS_NULL_INPUT; } if (CFG_GetSignParamBySchemes(ctx, ctx->peerInfo.peerSignHashAlg, &signAlg, &hashAlg) == false) { return HITLS_CONFIG_NO_SUITABLE_CIPHER_SUITE; } *sigType = signAlg; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_GetLocalSignScheme(const HITLS_Ctx *ctx, HITLS_SignHashAlgo *localSignScheme) { if (ctx == NULL || localSignScheme == NULL) { return HITLS_NULL_INPUT; } *localSignScheme = ctx->negotiatedInfo.signScheme; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_GetPeerSignScheme(const HITLS_Ctx *ctx, HITLS_SignHashAlgo *peerSignScheme) { if (ctx == NULL || peerSignScheme == NULL) { return HITLS_NULL_INPUT; } *peerSignScheme = ctx->peerInfo.peerSignHashAlg; return HITLS_SUCCESS; } #endif int32_t HITLS_SetEcGroups(HITLS_Ctx *ctx, uint16_t *lst, uint32_t groupSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetGroups(&(ctx->config.tlsConfig), lst, groupSize); } int32_t HITLS_SetSigalgsList(HITLS_Ctx *ctx, const uint16_t *signAlgs, uint16_t signAlgsSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetSignature(&(ctx->config.tlsConfig), signAlgs, signAlgsSize); } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_GetRenegotiationSupport(const HITLS_Ctx *ctx, uint8_t *isSupportRenegotiation) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetRenegotiationSupport(&(ctx->config.tlsConfig), isSupportRenegotiation); } #endif int32_t HITLS_SetEcPointFormats(HITLS_Ctx *ctx, const uint8_t *pointFormats, uint32_t pointFormatsSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetEcPointFormats(&(ctx->config.tlsConfig), pointFormats, pointFormatsSize); } int32_t HITLS_ClearChainCerts(HITLS_Ctx *ctx) { if (ctx == NULL || ctx->config.tlsConfig.certMgrCtx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_ClearChainCerts(&(ctx->config.tlsConfig)); } #ifdef HITLS_TLS_FEATURE_CERT_MODE int32_t HITLS_SetClientVerifySupport(HITLS_Ctx *ctx, bool support) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetClientVerifySupport(&(ctx->config.tlsConfig), support); } int32_t HITLS_SetNoClientCertSupport(HITLS_Ctx *ctx, bool support) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetNoClientCertSupport(&(ctx->config.tlsConfig), support); } #endif #ifdef HITLS_TLS_FEATURE_PHA int32_t HITLS_SetPostHandshakeAuthSupport(HITLS_Ctx *ctx, bool support) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetPostHandshakeAuthSupport(&(ctx->config.tlsConfig), support); } #endif #ifdef HITLS_TLS_FEATURE_CERT_MODE int32_t HITLS_SetVerifyNoneSupport(HITLS_Ctx *ctx, bool support) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetVerifyNoneSupport(&(ctx->config.tlsConfig), support); } #endif #if defined(HITLS_TLS_FEATURE_CERT_MODE) && defined(HITLS_TLS_FEATURE_RENEGOTIATION) int32_t HITLS_SetClientOnceVerifySupport(HITLS_Ctx *ctx, bool support) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetClientOnceVerifySupport(&(ctx->config.tlsConfig), support); } #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH int32_t HITLS_SetDhAutoSupport(HITLS_Ctx *ctx, bool support) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetDhAutoSupport(&(ctx->config.tlsConfig), support); } int32_t HITLS_SetTmpDh(HITLS_Ctx *ctx, HITLS_CRYPT_Key *dhPkey) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetTmpDh(&(ctx->config.tlsConfig), dhPkey); } #endif #if defined(HITLS_TLS_CONNECTION_INFO_NEGOTIATION) && defined(HITLS_TLS_FEATURE_SESSION) HITLS_CERT_Chain *HITLS_GetPeerCertChain(const HITLS_Ctx *ctx) { CERT_Pair *certPair = NULL; if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16477, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ctx null", 0, 0, 0, 0); return NULL; } int32_t ret = SESS_GetPeerCert(ctx->session, &certPair); if (ret != HITLS_SUCCESS || certPair == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16478, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ret %d, GetPeerCert fail", ret, 0, 0, 0); return NULL; } HITLS_CERT_Chain *certChain = SAL_CERT_PairGetChain(certPair); return certChain; } #endif #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION HITLS_TrustedCAList *HITLS_GetPeerCAList(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return ctx->peerInfo.caList; } #endif #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES HITLS_TrustedCAList *HITLS_GetCAList(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetCAList(&(ctx->config.tlsConfig)); } int32_t HITLS_SetCAList(HITLS_Ctx *ctx, HITLS_TrustedCAList *list) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetCAList(&(ctx->config.tlsConfig), list); } #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_GetSecureRenegotiationSupport(const HITLS_Ctx *ctx, uint8_t *isSecureRenegotiation) { if (ctx == NULL || isSecureRenegotiation == NULL) { return HITLS_NULL_INPUT; } *isSecureRenegotiation = (uint8_t)ctx->negotiatedInfo.isSecureRenegotiation; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_MAINTAIN_KEYLOG static int32_t Uint8ToHex(const uint8_t *srcBuf, size_t srcLen, size_t *offset, size_t destMaxSize, uint8_t *destBuf) { if (destMaxSize < 1) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16479, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "destMaxSize err", 0, 0, 0, 0); return HITLS_NULL_INPUT; } size_t length = (destMaxSize - 1) / 2; if (destBuf == NULL || offset == NULL || srcLen == 0 || srcBuf == NULL || length < srcLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16480, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_NULL_INPUT; } /* Initialize Offset */ size_t offsetTemp = 0u; /* Converting an Array to a Hexadecimal Character String */ for (size_t i = 0u; i < srcLen; i++) { if (sprintf_s((char *)&destBuf[offsetTemp], (destMaxSize - offsetTemp), "%02x", srcBuf[i]) == -1) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16481, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sprintf_s fail", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } offsetTemp += sizeof(uint16_t); if (offsetTemp >= destMaxSize) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16482, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "There's not enough memory", 0, 0, 0, 0); return HITLS_INVALID_INPUT; } } /* Update Offset */ *offset = offsetTemp; return HITLS_SUCCESS; } int32_t HITLS_LogSecret(HITLS_Ctx *ctx, const char *label, const uint8_t *secret, size_t secretLen) { if (ctx == NULL || label == NULL || secret == NULL || secretLen == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16483, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_NULL_INPUT; } if (ctx->globalConfig->keyLogCb == NULL) { return HITLS_SUCCESS; } size_t offset = 0; uint8_t *random = ctx->negotiatedInfo.clientRandom; uint32_t randomLen = RANDOM_SIZE; size_t labelLen = strlen(label); const uint8_t blankSpace = 0x20; // The lengths of random and secret need to be converted into hexadecimal so they are doubled. size_t outLen = labelLen + randomLen + randomLen + secretLen + secretLen + 3; uint8_t *outBuffer = (uint8_t *)BSL_SAL_Calloc((uint32_t)outLen, sizeof(uint8_t)); if (outBuffer == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16484, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } // Combine label, random, and secret into a character string separated by spaces and end with '\0'. (void)memcpy_s(outBuffer, outLen, label, labelLen); offset += labelLen; outBuffer[offset++] = blankSpace; size_t index = 0; // Convert random to a hexadecimal character string. int32_t ret = Uint8ToHex(random, randomLen, &index, outLen - offset, &outBuffer[offset]); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16485, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "random Uint8ToHex fail", 0, 0, 0, 0); BSL_SAL_FREE(outBuffer); return ret; } offset += index; outBuffer[offset++] = blankSpace; // Convert the master key buffer to a hexadecimal character string. ret = Uint8ToHex(secret, secretLen, &index, outLen - offset, &outBuffer[offset]); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16486, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "secret Uint8ToHex fail", 0, 0, 0, 0); BSL_SAL_FREE(outBuffer); return ret; } ctx->globalConfig->keyLogCb(ctx, (const char *)outBuffer); BSL_SAL_CleanseData(outBuffer, outLen); BSL_SAL_FREE(outBuffer); return HITLS_SUCCESS; } #endif /* HITLS_TLS_MAINTAIN_KEYLOG */ #ifdef HITLS_TLS_FEATURE_CERT_CB int32_t HITLS_SetCertCb(HITLS_Ctx *ctx, HITLS_CertCb certCb, void *arg) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetCertCb(&(ctx->config.tlsConfig), certCb, arg); } #endif /* HITLS_TLS_FEATURE_CERT_CB */ #ifdef HITLS_TLS_CONFIG_CERT_BUILD_CHAIN int32_t HITLS_BuildCertChain(HITLS_Ctx *ctx, HITLS_BUILD_CHAIN_FLAG flag) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_BuildCertChain(&(ctx->config.tlsConfig), flag); } #endif int32_t HITLS_CtrlSetVerifyParams(HITLS_Ctx *ctx, HITLS_CERT_Store *store, uint32_t cmd, int64_t in, void *inArg) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_CtrlSetVerifyParams(&(ctx->config.tlsConfig), store, cmd, in, inArg); } int32_t HITLS_CtrlGetVerifyParams(HITLS_Ctx *ctx, HITLS_CERT_Store *store, uint32_t cmd, void *out) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_CtrlGetVerifyParams(&(ctx->config.tlsConfig), store, cmd, out); }
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_create.c
C
unknown
24,472
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_error.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "hitls_type.h" #include "hitls_config.h" #include "tls.h" #ifdef HITLS_TLS_FEATURE_SESSION #include "session.h" #endif #include "cert_method.h" #include "record.h" #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_GetNegotiatedVersion(const HITLS_Ctx *ctx, uint16_t *version) { if (ctx == NULL || version == NULL) { return HITLS_NULL_INPUT; } *version = ctx->negotiatedInfo.version; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_ALL int32_t HITLS_GetMaxProtoVersion(const HITLS_Ctx *ctx, uint16_t *maxVersion) { if (ctx == NULL || maxVersion == NULL) { return HITLS_NULL_INPUT; } *maxVersion = ctx->config.tlsConfig.maxVersion; return HITLS_SUCCESS; } int32_t HITLS_GetMinProtoVersion(const HITLS_Ctx *ctx, uint16_t *minVersion) { if (ctx == NULL || minVersion == NULL) { return HITLS_NULL_INPUT; } *minVersion = ctx->config.tlsConfig.minVersion; return HITLS_SUCCESS; } int32_t HITLS_SetMinProtoVersion(HITLS_Ctx *ctx, uint16_t version) { if (ctx == NULL) { return HITLS_NULL_INPUT; } uint16_t maxVersion = ctx->config.tlsConfig.maxVersion; return HITLS_CFG_SetVersion(&(ctx->config.tlsConfig), version, maxVersion); } int32_t HITLS_SetMaxProtoVersion(HITLS_Ctx *ctx, uint16_t version) { if (ctx == NULL) { return HITLS_NULL_INPUT; } uint16_t minVersion = ctx->config.tlsConfig.minVersion; return HITLS_CFG_SetVersion(&(ctx->config.tlsConfig), minVersion, version); } #endif #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_IsAead(const HITLS_Ctx *ctx, uint8_t *isAead) { if (ctx == NULL) { return HITLS_NULL_INPUT; } /* Check whether the input parameter is empty. The system does not need to check whether the input parameter is * empty */ return HITLS_CIPHER_IsAead(&(ctx->negotiatedInfo.cipherSuiteInfo), isAead); } #endif #ifdef HITLS_TLS_PROTO_DTLS int32_t HITLS_IsDtls(const HITLS_Ctx *ctx, uint8_t *isDtls) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_IsDtls(&(ctx->config.tlsConfig), isDtls); } #endif #ifdef HITLS_TLS_FEATURE_SESSION int32_t HITLS_IsSessionReused(HITLS_Ctx *ctx, uint8_t *isReused) { if (ctx == NULL || isReused == NULL) { return HITLS_NULL_INPUT; } *isReused = (uint8_t)ctx->negotiatedInfo.isResume; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_SESSION_ID int32_t HITLS_SetSessionIdCtx(HITLS_Ctx *ctx, const uint8_t *sessionIdCtx, uint32_t len) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetSessionIdCtx(&ctx->config.tlsConfig, sessionIdCtx, len); } #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET int32_t HITLS_GetSessionTicketKey(const HITLS_Ctx *ctx, uint8_t *key, uint32_t keySize, uint32_t *outSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetSessionTicketKey(&ctx->config.tlsConfig, key, keySize, outSize); } int32_t HITLS_SetSessionTicketKey(HITLS_Ctx *ctx, const uint8_t *key, uint32_t keySize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetSessionTicketKey(&ctx->config.tlsConfig, key, keySize); } #endif int32_t HITLS_SetVerifyResult(HITLS_Ctx *ctx, HITLS_ERROR verifyResult) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->peerInfo.verifyResult = verifyResult; return HITLS_SUCCESS; } int32_t HITLS_GetVerifyResult(const HITLS_Ctx *ctx, HITLS_ERROR *verifyResult) { if (ctx == NULL || verifyResult == NULL) { return HITLS_NULL_INPUT; } *verifyResult = ctx->peerInfo.verifyResult; return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HITLS_SetDtlsTimerCb(HITLS_Ctx *ctx, HITLS_DtlsTimerCb cb) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetDtlsTimerCb(&(ctx->config.tlsConfig), cb); } #endif #if defined(HITLS_TLS_CONNECTION_INFO_NEGOTIATION) && defined(HITLS_TLS_FEATURE_SESSION) HITLS_CERT_X509 *HITLS_GetPeerCertificate(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } CERT_Pair *peerCert = NULL; int32_t ret = SESS_GetPeerCert(ctx->session, &peerCert); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17157, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetPeerCert fail", 0, 0, 0, 0); return NULL; } HITLS_CERT_X509 *cert = SAL_CERT_PairGetX509(peerCert); /* Certificate reference increments by one */ return cert == NULL ? NULL : SAL_CERT_X509Ref(ctx->config.tlsConfig.certMgrCtx, cert); } #endif int32_t HITLS_SetQuietShutdown(HITLS_Ctx *ctx, int32_t mode) { if (ctx == NULL) { return HITLS_NULL_INPUT; } // The mode value 0 indicates that the quiet disconnection mode is disabled. The mode value 1 indicates that the // quiet disconnection mode is enabled if (mode != 0 && mode != 1) { return HITLS_CONFIG_INVALID_SET; } ctx->config.tlsConfig.isQuietShutdown = (mode != 0); return HITLS_SUCCESS; } int32_t HITLS_GetQuietShutdown(const HITLS_Ctx *ctx, int32_t *mode) { if (ctx == NULL || mode == NULL) { return HITLS_NULL_INPUT; } *mode = (int32_t)ctx->config.tlsConfig.isQuietShutdown; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_GetRenegotiationState(const HITLS_Ctx *ctx, uint8_t *isRenegotiationState) { if (ctx == NULL || isRenegotiationState == NULL) { return HITLS_NULL_INPUT; } *isRenegotiationState = (uint8_t)ctx->negotiatedInfo.isRenegotiation; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONFIG_STATE int32_t HITLS_GetRwstate(const HITLS_Ctx *ctx, uint8_t *rwstate) { if (ctx == NULL || rwstate == NULL) { return HITLS_NULL_INPUT; } *rwstate = ctx->rwstate; return HITLS_SUCCESS; } #endif int32_t HITLS_SetShutdownState(HITLS_Ctx *ctx, uint32_t mode) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->shutdownState = mode; return HITLS_SUCCESS; } int32_t HITLS_GetShutdownState(const HITLS_Ctx *ctx, uint32_t *mode) { if (ctx == NULL || mode == NULL) { return HITLS_NULL_INPUT; } *mode = ctx->shutdownState; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_CERT_MODE int32_t HITLS_GetClientVerifySupport(HITLS_Ctx *ctx, uint8_t *isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetClientVerifySupport(&(ctx->config.tlsConfig), isSupport); } int32_t HITLS_GetNoClientCertSupport(HITLS_Ctx *ctx, uint8_t *isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetNoClientCertSupport(&(ctx->config.tlsConfig), isSupport); } #endif #ifdef HITLS_TLS_FEATURE_PHA int32_t HITLS_GetPostHandshakeAuthSupport(HITLS_Ctx *ctx, uint8_t *isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetPostHandshakeAuthSupport(&(ctx->config.tlsConfig), isSupport); } #endif #ifdef HITLS_TLS_FEATURE_CERT_MODE int32_t HITLS_GetVerifyNoneSupport(HITLS_Ctx *ctx, uint8_t *isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetVerifyNoneSupport(&(ctx->config.tlsConfig), isSupport); } #endif #if defined(HITLS_TLS_FEATURE_CERT_MODE) && defined(HITLS_TLS_FEATURE_RENEGOTIATION) int32_t HITLS_GetClientOnceVerifySupport(HITLS_Ctx *ctx, uint8_t *isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetClientOnceVerifySupport(&(ctx->config.tlsConfig), isSupport); } #endif #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_ClearRenegotiationNum(HITLS_Ctx *ctx, uint32_t *renegotiationNum) { if (ctx == NULL || renegotiationNum == NULL) { return HITLS_NULL_INPUT; } *renegotiationNum = ctx->negotiatedInfo.renegotiationNum; ctx->negotiatedInfo.renegotiationNum = 0; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_MODE int32_t HITLS_SetModeSupport(HITLS_Ctx *ctx, uint32_t mode) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetModeSupport(&(ctx->config.tlsConfig), mode); } int32_t HITLS_ClearModeSupport(HITLS_Ctx *ctx, uint32_t mode) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_ClearModeSupport(&(ctx->config.tlsConfig), mode); } int32_t HITLS_GetModeSupport(const HITLS_Ctx *ctx, uint32_t *mode) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetModeSupport(&(ctx->config.tlsConfig), mode); } #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC int32_t HITLS_SetEncryptThenMac(HITLS_Ctx *ctx, uint32_t encryptThenMacType) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetEncryptThenMac(&(ctx->config.tlsConfig), encryptThenMacType); } int32_t HITLS_GetEncryptThenMac(const HITLS_Ctx *ctx, uint32_t *encryptThenMacType) { if (ctx == NULL || encryptThenMacType == NULL) { return HITLS_NULL_INPUT; } // Returns the negotiated value if it has been negotiated if (ctx->negotiatedInfo.version > 0) { *encryptThenMacType = (uint32_t)ctx->negotiatedInfo.isEncryptThenMac; return HITLS_SUCCESS; } else { return HITLS_CFG_GetEncryptThenMac(&(ctx->config.tlsConfig), encryptThenMacType); } } #endif #ifdef HITLS_TLS_FEATURE_SNI int32_t HITLS_SetServerName(HITLS_Ctx *ctx, uint8_t *serverName, uint32_t serverNameStrlen) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetServerName(&(ctx->config.tlsConfig), serverName, serverNameStrlen); } #endif int32_t HITLS_SetCipherServerPreference(HITLS_Ctx *ctx, bool isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetCipherServerPreference(&(ctx->config.tlsConfig), isSupport); } int32_t HITLS_GetCipherServerPreference(const HITLS_Ctx *ctx, bool *isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetCipherServerPreference(&(ctx->config.tlsConfig), isSupport); } int32_t HITLS_SetRenegotiationSupport(HITLS_Ctx *ctx, bool isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetRenegotiationSupport(&(ctx->config.tlsConfig), isSupport); } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_SetClientRenegotiateSupport(HITLS_Ctx *ctx, bool isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetClientRenegotiateSupport(&(ctx->config.tlsConfig), isSupport); } #endif #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t HITLS_SetLegacyRenegotiateSupport(HITLS_Ctx *ctx, bool isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetLegacyRenegotiateSupport(&(ctx->config.tlsConfig), isSupport); } #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #ifdef HITLS_TLS_FEATURE_SESSION_TICKET int32_t HITLS_SetSessionTicketSupport(HITLS_Ctx *ctx, bool isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetSessionTicketSupport(&(ctx->config.tlsConfig), isSupport); } int32_t HITLS_GetSessionTicketSupport(const HITLS_Ctx *ctx, uint8_t *isSupport) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetSessionTicketSupport(&(ctx->config.tlsConfig), isSupport); } #endif int32_t HITLS_SetEmptyRecordsNum(HITLS_Ctx *ctx, uint32_t emptyNum) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetEmptyRecordsNum(&(ctx->config.tlsConfig), emptyNum); } int32_t HITLS_GetEmptyRecordsNum(const HITLS_Ctx *ctx, uint32_t *emptyNum) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetEmptyRecordsNum(&(ctx->config.tlsConfig), emptyNum); } #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT int32_t HITLS_SetMaxSendFragment(HITLS_Ctx *ctx, uint16_t maxSendFragment) { if (ctx == NULL) { return HITLS_NULL_INPUT; } if (ctx->recCtx != NULL && ctx->recCtx->outBuf != NULL && ctx->recCtx->outBuf->start != ctx->recCtx->outBuf->end) { return HITLS_REC_NORMAL_IO_BUSY; } return HITLS_CFG_SetMaxSendFragment(&(ctx->config.tlsConfig), maxSendFragment); } int32_t HITLS_GetMaxSendFragment(const HITLS_Ctx *ctx, uint16_t *maxSendFragment) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetMaxSendFragment(&(ctx->config.tlsConfig), maxSendFragment); } #endif #ifdef HITLS_TLS_FEATURE_REC_INBUFFER_SIZE int32_t HITLS_SetRecInbufferSize(HITLS_Ctx *ctx, uint32_t recInbufferSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetRecInbufferSize(&(ctx->config.tlsConfig), recInbufferSize); } int32_t HITLS_GetRecInbufferSize(const HITLS_Ctx *ctx, uint32_t *recInbufferSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetRecInbufferSize(&(ctx->config.tlsConfig), recInbufferSize); } #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET int32_t HITLS_SetTicketNums(HITLS_Ctx *ctx, uint32_t ticketNums) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetTicketNums(&ctx->config.tlsConfig, ticketNums); } uint32_t HITLS_GetTicketNums(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetTicketNums(&ctx->config.tlsConfig); } #endif #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t HITLS_SetFlightTransmitSwitch(HITLS_Ctx *ctx, uint8_t isEnable) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetFlightTransmitSwitch(&(ctx->config.tlsConfig), isEnable); } int32_t HITLS_GetFlightTransmitSwitch(const HITLS_Ctx *ctx, uint8_t *isEnable) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetFlightTransmitSwitch(&(ctx->config.tlsConfig), isEnable); } #endif #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HITLS_SetDtlsCookieExangeSupport(HITLS_Ctx *ctx, bool isEnable) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetDtlsCookieExchangeSupport(&(ctx->config.tlsConfig), isEnable); } int32_t HITLS_GetDtlsCookieExangeSupport(const HITLS_Ctx *ctx, bool *isEnable) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetDtlsCookieExchangeSupport(&(ctx->config.tlsConfig), isEnable); } #endif #ifdef HITLS_TLS_CONFIG_CERT /** * @ingroup hitls * @brief Set the maximum size of the certificate chain that can be sent by the peer end. * * @param ctx [IN/OUT] TLS connection handle * @param maxSize [IN] Set the maximum size of the certificate chain that can be sent by the peer end. * @retval HITLS_NULL_INPUT The input parameter pointer is null. * @retval HITLS_SUCCESS succeeded. */ int32_t HITLS_SetMaxCertList(HITLS_Ctx *ctx, uint32_t maxSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetMaxCertList(&(ctx->config.tlsConfig), maxSize); } /** * @ingroup hitls * @brief Obtain the maximum size of the certificate chain that can be sent by the peer end. * * @param ctx [IN] TLS connection handle * @param maxSize [OUT] Maximum size of the certificate chain that can be sent by the peer end * @retval HITLS_NULL_INPUT The input parameter pointer is null. * @retval HITLS_SUCCESS succeeded. */ int32_t HITLS_GetMaxCertList(const HITLS_Ctx *ctx, uint32_t *maxSize) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetMaxCertList(&(ctx->config.tlsConfig), maxSize); } #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH int32_t HITLS_SetTmpDhCb(HITLS_Ctx *ctx, HITLS_DhTmpCb cb) { if (ctx == NULL || cb == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetTmpDhCb(&(ctx->config.tlsConfig), cb); } #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ #ifdef HITLS_TLS_CONFIG_RECORD_PADDING int32_t HITLS_SetRecordPaddingCb(HITLS_Ctx *ctx, HITLS_RecordPaddingCb cb) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetRecordPaddingCb(&(ctx->config.tlsConfig), cb); } HITLS_RecordPaddingCb HITLS_GetRecordPaddingCb(HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetRecordPaddingCb(&(ctx->config.tlsConfig)); } int32_t HITLS_SetRecordPaddingCbArg(HITLS_Ctx *ctx, void *arg) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetRecordPaddingCbArg(&(ctx->config.tlsConfig), arg); } void *HITLS_GetRecordPaddingCbArg(HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return HITLS_CFG_GetRecordPaddingCbArg(&(ctx->config.tlsConfig)); } #endif #ifdef HITLS_TLS_CONFIG_KEY_USAGE int32_t HITLS_SetCheckKeyUsage(HITLS_Ctx *ctx, bool isCheck) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetCheckKeyUsage(&(ctx->config.tlsConfig), isCheck); } #endif #ifdef HITLS_TLS_PROTO_TLS13 int32_t HITLS_SetMiddleBoxCompat(HITLS_Ctx *ctx, bool isMiddleBox) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetMiddleBoxCompat(&(ctx->config.tlsConfig), isMiddleBox); } int32_t HITLS_GetMiddleBoxCompat(HITLS_Ctx *ctx, bool *isMiddleBox) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_GetMiddleBoxCompat(&(ctx->config.tlsConfig), isMiddleBox); } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_ctrl.c
C
unknown
18,324
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_INDICATOR #include <stddef.h> #include "tls.h" #include "hitls_error.h" #include "bsl_err_internal.h" #include "hitls_debug.h" int32_t HITLS_SetInfoCb(HITLS_Ctx *ctx, HITLS_InfoCb callback) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->config.tlsConfig.infoCb = callback; return HITLS_SUCCESS; } HITLS_InfoCb HITLS_GetInfoCb(const HITLS_Ctx *ctx) { if (ctx == NULL) { return NULL; } return ctx->config.tlsConfig.infoCb; } int32_t HITLS_CFG_SetInfoCb(HITLS_Config *config, HITLS_InfoCb callback) { /* support NULL callback */ if (config == NULL) { return HITLS_NULL_INPUT; } config->infoCb = callback; return HITLS_SUCCESS; } HITLS_InfoCb HITLS_CFG_GetInfoCb(const HITLS_Config *config) { if (config == NULL) { return NULL; } return config->infoCb; } int32_t HITLS_SetMsgCb(HITLS_Ctx *ctx, HITLS_MsgCb callback) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetMsgCb(&(ctx->config.tlsConfig), callback); } int32_t HITLS_CFG_SetMsgCb(HITLS_Config *config, HITLS_MsgCb callback) { /* support NULL callback */ if (config == NULL) { return HITLS_NULL_INPUT; } config->msgCb = callback; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetMsgCbArg(HITLS_Config *config, void *arg) { if (config == NULL) { return HITLS_NULL_INPUT; } config->msgArg = arg; return HITLS_SUCCESS; } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_debug.c
C
unknown
2,069
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_err_internal.h" #include "hitls.h" #include "hitls_error.h" #include "hitls_type.h" #include "tls.h" #include "hs.h" #include "alert.h" #include "conn_init.h" #include "conn_common.h" #include "rec.h" #include "app.h" #include "bsl_uio.h" #include "record.h" #include "hs_ctx.h" #include "hs_state_recv.h" #include "hs_state_send.h" #include "hs_common.h" #ifdef HITLS_TLS_PROTO_DTLS12 #define DTLS_MAX_MTU_OVERHEAD 48 /* Max overhead, ipv6 40 + udp 8 */ #endif #define DATA_MAX_LENGTH 1024 static int32_t ConnectEventInIdleState(HITLS_Ctx *ctx) { ctx->isClient = true; // Set the configuration as a client int32_t ret = CONN_Init(ctx); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16487, "CONN_Init fail"); } ChangeConnState(ctx, CM_STATE_HANDSHAKING); // In idle state, after initialization, the handshake process is directly started. Therefore, the handshake status // function is directly invoked. return CommonEventInHandshakingState(ctx); } static int32_t AcceptEventInIdleState(HITLS_Ctx *ctx) { ctx->isClient = false; // Set the configuration as the server int32_t ret = CONN_Init(ctx); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16488, "CONN_Init fail"); } ChangeConnState(ctx, CM_STATE_HANDSHAKING); // In idle state, after initialization, the handshake process is directly started. Therefore, the handshake status // function is directly invoked. return CommonEventInHandshakingState(ctx); } static int32_t EstablishEventInTransportingState(HITLS_Ctx *ctx) { (void)ctx; // In the renegotiation state, the renegotiation handshake procedure is started. return HITLS_SUCCESS; } static int32_t EstablishEventInRenegotiationState(HITLS_Ctx *ctx) { #ifdef HITLS_TLS_FEATURE_RENEGOTIATION // In the renegotiation state, the renegotiation handshake procedure is started. int32_t ret = CommonEventInRenegotiationState(ctx); if (ret != HITLS_SUCCESS) { if (ret == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG && ctx->state != CM_STATE_ALERTED) { // In this case, the HITLS initiates renegotiation, but the peer end does not respond to the renegotiation // request but returns an APP message. In this case, the success message should be returned. return HITLS_SUCCESS; } return ret; } return HITLS_SUCCESS; #else (void)ctx; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15405, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "invalid conn states %d", CM_STATE_RENEGOTIATION, NULL, NULL, NULL); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t CloseEventInRenegotiationState(HITLS_Ctx *ctx) { #ifdef HITLS_TLS_FEATURE_RENEGOTIATION if ((ctx->shutdownState & HITLS_SENT_SHUTDOWN) == 0) { ALERT_Send(ctx, ALERT_LEVEL_WARNING, ALERT_CLOSE_NOTIFY); int32_t ret = ALERT_Flush(ctx); if (ret != HITLS_SUCCESS) { ChangeConnState(ctx, CM_STATE_ALERTED); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16528, "ALERT_Flush fail"); } ctx->shutdownState |= HITLS_SENT_SHUTDOWN; } /* In the renegotiation state, if the HITLS_Close function is called, the connection is directly disconnected * and read/write operations are not allowed. */ ctx->shutdownState |= HITLS_RECEIVED_SHUTDOWN; ChangeConnState(ctx, CM_STATE_CLOSED); return HITLS_SUCCESS; #else (void)ctx; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15406, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "invalid conn states %d", CM_STATE_RENEGOTIATION, NULL, NULL, NULL); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t EstablishEventInAlertedState(HITLS_Ctx *ctx) { (void)ctx; // Directly return a message indicating that the link status is abnormal. return HITLS_CM_LINK_FATAL_ALERTED; } static int32_t EstablishEventInClosedState(HITLS_Ctx *ctx) { (void)ctx; // Directly return a message indicating that the link status is abnormal. return HITLS_CM_LINK_CLOSED; } static int32_t CloseEventInIdleState(HITLS_Ctx *ctx) { ChangeConnState(ctx, CM_STATE_CLOSED); ctx->shutdownState |= (HITLS_SENT_SHUTDOWN | HITLS_RECEIVED_SHUTDOWN); return HITLS_SUCCESS; } static int32_t CloseEventInHandshakingState(HITLS_Ctx *ctx) { if ((ctx->shutdownState & HITLS_SENT_SHUTDOWN) == 0) { ALERT_Send(ctx, ALERT_LEVEL_WARNING, ALERT_CLOSE_NOTIFY); int32_t ret = ALERT_Flush(ctx); if (ret != HITLS_SUCCESS) { ChangeConnState(ctx, CM_STATE_ALERTED); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16463, "ALERT_Flush fail"); } ctx->shutdownState |= HITLS_SENT_SHUTDOWN; } /* In the handshaking state, if the close function is called, the connection is directly disconnected * and read/write operations are not allowed. */ ctx->shutdownState |= HITLS_RECEIVED_SHUTDOWN; ChangeConnState(ctx, CM_STATE_CLOSED); return HITLS_SUCCESS; } static int32_t CloseEventInTransportingState(HITLS_Ctx *ctx) { if ((ctx->shutdownState & HITLS_SENT_SHUTDOWN) == 0) { ALERT_Send(ctx, ALERT_LEVEL_WARNING, ALERT_CLOSE_NOTIFY); int32_t ret = ALERT_Flush(ctx); if (ret != HITLS_SUCCESS) { ChangeConnState(ctx, CM_STATE_ALERTING); return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16490, "ALERT_Flush fail"); } ctx->shutdownState |= HITLS_SENT_SHUTDOWN; } ChangeConnState(ctx, CM_STATE_CLOSED); return HITLS_SUCCESS; } static int32_t CloseEventInAlertingState(HITLS_Ctx *ctx) { /* If there are fatal alerts that are not sent, the system continues to send the alert. Otherwise, the system sends * the close_notify alert */ ALERT_Send(ctx, ALERT_LEVEL_WARNING, ALERT_CLOSE_NOTIFY); return CommonEventInAlertingState(ctx); } static int32_t CloseEventInAlertedState(HITLS_Ctx *ctx) { /* * 1. Receive a fatal alert from the peer end. * 2. A fatal alert has been sent to the peer end. * 3. Receive the close notification from the peer end. */ // Read and write operations are not allowed in the alerted state ChangeConnState(ctx, CM_STATE_CLOSED); ctx->shutdownState |= (HITLS_SENT_SHUTDOWN | HITLS_RECEIVED_SHUTDOWN); return HITLS_SUCCESS; } static int32_t CloseEventInClosedState(HITLS_Ctx *ctx) { int32_t ret; /* When a user invokes the close function for the first time, a close notify message is sent to the peer end. When * the user invokes the close function for the second time, the user attempts to receive the close notify message. */ if ((ctx->shutdownState & HITLS_RECEIVED_SHUTDOWN) == 0) { uint8_t data[DATA_MAX_LENGTH]; // Discard the received APP message. uint32_t readLen = 0; ALERT_CleanInfo(ctx); ret = APP_Read(ctx, data, sizeof(data), &readLen); if (ret == HITLS_SUCCESS) { return HITLS_SUCCESS; } if (ALERT_GetFlag(ctx) == false) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16491, "Read fail"); } int32_t alertRet = AlertEventProcess(ctx); if (alertRet == HITLS_CM_LINK_CLOSED) { return HITLS_SUCCESS; } if (alertRet != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(alertRet, BINLOG_ID16492, "AlertEventProcess fail"); } return ret; } if ((ctx->shutdownState & HITLS_SENT_SHUTDOWN) == 0) { ALERT_Send(ctx, ALERT_LEVEL_WARNING, ALERT_CLOSE_NOTIFY); ret = ALERT_Flush(ctx); if (ret != HITLS_SUCCESS) { ChangeConnState(ctx, CM_STATE_ALERTING); return ret; } ctx->shutdownState |= HITLS_SENT_SHUTDOWN; } ChangeConnState(ctx, CM_STATE_CLOSED); return HITLS_SUCCESS; } // Check and process the CTX status before HITLS_Connect and HITLS_Accept. int32_t ProcessCtxState(HITLS_Ctx *ctx) { int32_t ret; if (ctx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16493, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); return HITLS_NULL_INPUT; } /* Process the unsent alert message first, and then enter the corresponding state processing function based on the * processing result */ if (GetConnState(ctx) == CM_STATE_ALERTING) { ret = CommonEventInAlertingState(ctx); if (ret != HITLS_SUCCESS) { /* If the alert fails to be sent, a response is returned to the user */ return ret; } } if ((GetConnState(ctx) >= CM_STATE_END) || (GetConnState(ctx) == CM_STATE_ALERTING)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16494, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); /* If the alert message is sent successfully, the system switches to another state. Otherwise, an internal * exception occurs */ return HITLS_INTERNAL_EXCEPTION; } return HITLS_SUCCESS; } int32_t HITLS_SetEndPoint(HITLS_Ctx *ctx, bool isClient) { if (ctx == NULL) { return HITLS_NULL_INPUT; } if (GetConnState(ctx) != CM_STATE_IDLE) { return HITLS_MSG_HANDLE_STATE_ILLEGAL; } ctx->isClient = isClient; int32_t ret = CONN_Init(ctx); if (ret != HITLS_SUCCESS) { return ret; } ChangeConnState(ctx, CM_STATE_HANDSHAKING); return HITLS_SUCCESS; } static int32_t ProcessEvent(HITLS_Ctx *ctx, ManageEventProcess proc) { return proc(ctx); } int32_t HITLS_Connect(HITLS_Ctx *ctx) { int32_t ret = ProcessCtxState(ctx); // Process the alerting state if (ret != HITLS_SUCCESS) { return ret; } ctx->allowAppOut = false; ManageEventProcess connectEventProcess[CM_STATE_END] = { ConnectEventInIdleState, CommonEventInHandshakingState, EstablishEventInTransportingState, EstablishEventInRenegotiationState, NULL, // The alerting phase has been processed in the ProcessCtxState function EstablishEventInAlertedState, EstablishEventInClosedState }; ManageEventProcess proc = connectEventProcess[GetConnState(ctx)]; return ProcessEvent(ctx, proc); } int32_t HITLS_Accept(HITLS_Ctx *ctx) { int32_t ret = ProcessCtxState(ctx); if (ret != HITLS_SUCCESS) { return ret; } ctx->allowAppOut = false; #ifdef HITLS_TLS_FEATURE_PHA ret = CommonCheckPostHandshakeAuth(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif ManageEventProcess acceptEventProcess[CM_STATE_END] = { AcceptEventInIdleState, CommonEventInHandshakingState, EstablishEventInTransportingState, EstablishEventInRenegotiationState, NULL, EstablishEventInAlertedState, EstablishEventInClosedState }; ManageEventProcess proc = acceptEventProcess[GetConnState(ctx)]; return ProcessEvent(ctx, proc); } int32_t HITLS_Close(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->userShutDown = 1; if (ctx->config.tlsConfig.isQuietShutdown) { ctx->shutdownState |= (HITLS_SENT_SHUTDOWN | HITLS_RECEIVED_SHUTDOWN); ChangeConnState(ctx, CM_STATE_CLOSED); return HITLS_SUCCESS; } ManageEventProcess closeEventProcess[CM_STATE_END] = { CloseEventInIdleState, CloseEventInHandshakingState, // Notify is sent to the peer end when the close interface is invoked during and // after link establishment. CloseEventInTransportingState, // Therefore, the same function is used for processing. CloseEventInRenegotiationState, // In the renegotiation process, invoking the close function also sends a notify // message to the peer end. CloseEventInAlertingState, CloseEventInAlertedState, CloseEventInClosedState}; if (GetConnState(ctx) >= CM_STATE_END) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16497, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); return HITLS_INTERNAL_EXCEPTION; } int32_t ret; do { ManageEventProcess proc = closeEventProcess[GetConnState(ctx)]; ret = ProcessEvent(ctx, proc); if (ret != HITLS_SUCCESS) { return ret; } } while (GetConnState(ctx) != CM_STATE_CLOSED); return HITLS_SUCCESS; } int32_t HITLS_GetError(const HITLS_Ctx *ctx, int32_t ret) { if (ctx == NULL) { /* Unknown error */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_ERR_SYSCALL, BINLOG_ID16498, "ctx null"); } /* No internal error occurs in the SSL */ if (ret == HITLS_SUCCESS) { return HITLS_SUCCESS; } if (ret == HITLS_CALLBACK_CLIENT_HELLO_RETRY) { return HITLS_WANT_CLIENT_HELLO_CB; } if (ret == HITLS_CALLBACK_CERT_RETRY) { return HITLS_WANT_X509_LOOKUP; } /* HANDSHAKING state */ if (ctx->state == CM_STATE_HANDSHAKING) { /* In non-blocking mode, I/O read/write failure is acceptable and link establishment is allowed */ if (ret == HITLS_REC_NORMAL_IO_BUSY || ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY) { return (ctx->isClient == true) ? HITLS_WANT_CONNECT : HITLS_WANT_ACCEPT; } /* Unacceptable exceptions occur on the underlying I/O */ if (ret == HITLS_REC_ERR_IO_EXCEPTION) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_ERR_SYSCALL, BINLOG_ID16499, "Unacceptable exceptions occured"); } /* The TLS protocol is incorrect */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_ERR_TLS, BINLOG_ID16500, "TLS protocol err"); } /* TRANSPORTING state */ if (ctx->state == CM_STATE_TRANSPORTING) { /* An I/O read/write failure occurs in non-blocking mode. This failure is acceptable and data can be written */ if (ret == HITLS_REC_NORMAL_IO_BUSY) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_WANT_WRITE, BINLOG_ID16501, "This failure is acceptable"); } /* An I/O read/write failure occurs in non-blocking mode. This failure is acceptable and data can be read * continuously */ if (ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_WANT_READ, BINLOG_ID16502, "This failure is acceptable"); } /* Unacceptable exceptions occur on the underlying I/O */ if (ret == HITLS_REC_ERR_IO_EXCEPTION) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_ERR_SYSCALL, BINLOG_ID16503, "Unacceptable exceptions occured"); } /* The TLS protocol is incorrect */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_ERR_TLS, BINLOG_ID16504, "TLS protocol err"); } /* ALERTING state */ if (ctx->state == CM_STATE_ALERTING) { if (ret == HITLS_REC_NORMAL_IO_BUSY) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_WANT_WRITE, BINLOG_ID16505, "This failure is acceptable"); } if (ret == HITLS_REC_NORMAL_RECV_BUF_EMPTY) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_WANT_READ, BINLOG_ID16506, "This failure is acceptable"); } } /* ALERTED state ,indicating that the TLS protocol is faulty and the link is abnormal */ if (ctx->state == CM_STATE_ALERTED) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_ERR_TLS, BINLOG_ID16507, "TLS protocol is faulty"); } /* Unknown error */ return RETURN_ERROR_NUMBER_PROCESS(HITLS_ERR_SYSCALL, BINLOG_ID16508, "unknown error"); } #ifdef HITLS_TLS_CONFIG_STATE int32_t HITLS_IsHandShakeDone(const HITLS_Ctx *ctx, uint8_t *isDone) { if (ctx == NULL || isDone == NULL) { return HITLS_NULL_INPUT; } *isDone = 0; if (ctx->state == CM_STATE_TRANSPORTING) { *isDone = 1; } return HITLS_SUCCESS; } int32_t HITLS_GetHandShakeState(const HITLS_Ctx *ctx, uint32_t *state) { if (ctx == NULL || state == NULL) { return HITLS_NULL_INPUT; } uint32_t hsState = TLS_IDLE; /* In initialization state */ if (ctx->state == CM_STATE_IDLE) { hsState = TLS_IDLE; } /* The link has been set up */ if (ctx->state == CM_STATE_TRANSPORTING) { hsState = TLS_CONNECTED; } /* The link is being established. If hsctx is not empty, obtain the status */ if (ctx->state == CM_STATE_HANDSHAKING || ctx->state == CM_STATE_RENEGOTIATION) { hsState = HS_GetState(ctx); } if (ctx->state == CM_STATE_ALERTING) { /* If hsCtx is not empty, it indicates that the link is being established. Obtain the corresponding status */ if (ctx->hsCtx != NULL) { hsState = HS_GetState(ctx); } else { /* After the link is established, the hsCtx is released. In this case, the hsCtx is in connected state */ hsState = TLS_CONNECTED; } } if (ctx->state == CM_STATE_ALERTED || ctx->state == CM_STATE_CLOSED) { if (ctx->preState == CM_STATE_IDLE && ctx->hsCtx == NULL) { hsState = TLS_IDLE; } else if (ctx->hsCtx != NULL) { /* If the value of ctx->hsCtx is not NULL, it indicates that the link is being established */ hsState = HS_GetState(ctx); } else { /* If hsCtx is NULL, the link has been established */ hsState = TLS_CONNECTED; } } *state = hsState; return HITLS_SUCCESS; } int32_t HITLS_IsHandShaking(const HITLS_Ctx *ctx, uint8_t *isHandShaking) { if (ctx == NULL || isHandShaking == NULL) { return HITLS_NULL_INPUT; } *isHandShaking = 0; uint32_t state = GetConnState(ctx); if ((state == CM_STATE_HANDSHAKING) || (state == CM_STATE_RENEGOTIATION)) { *isHandShaking = 1; } return HITLS_SUCCESS; } int32_t HITLS_IsBeforeHandShake(const HITLS_Ctx *ctx, uint8_t *isBefore) { if (ctx == NULL || isBefore == NULL) { return HITLS_NULL_INPUT; } *isBefore = 0; if (GetConnState(ctx) == CM_STATE_IDLE) { *isBefore = 1; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_CONFIG_STATE */ #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HITLS_SetLinkMtu(HITLS_Ctx *ctx, uint16_t linkMtu) { if (ctx == NULL) { return HITLS_NULL_INPUT; } if (linkMtu < DTLS_MIN_MTU) { return HITLS_CONFIG_INVALID_LENGTH; } ctx->config.linkMtu = linkMtu; return HITLS_SUCCESS; } int32_t HITLS_SetMtu(HITLS_Ctx *ctx, uint16_t mtu) { if (ctx == NULL) { return HITLS_NULL_INPUT; } if (mtu < DTLS_MIN_MTU - DTLS_MAX_MTU_OVERHEAD) { return HITLS_CONFIG_INVALID_LENGTH; } ctx->config.pmtu = mtu; ctx->mtuModified = true; return HITLS_SUCCESS; } int32_t HITLS_SetNoQueryMtu(HITLS_Ctx *ctx, bool noQueryMtu) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->noQueryMtu = noQueryMtu; return HITLS_SUCCESS; } int32_t HITLS_GetNeedQueryMtu(HITLS_Ctx *ctx, bool *needQueryMtu) { if (ctx == NULL || needQueryMtu == NULL) { return HITLS_NULL_INPUT; } *needQueryMtu = ctx->needQueryMtu; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */ #ifdef HITLS_TLS_CONNECTION_INFO_NEGOTIATION int32_t HITLS_GetClientVersion(const HITLS_Ctx *ctx, uint16_t *clientVersion) { if (ctx == NULL || clientVersion == NULL) { return HITLS_NULL_INPUT; } *clientVersion = ctx->negotiatedInfo.clientVersion; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONFIG_STATE const char *HITLS_GetStateString(uint32_t state) { return HS_GetStateStr(state); } #endif int32_t HITLS_DoHandShake(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } if (ctx->isClient) { return HITLS_Connect(ctx); } else { return HITLS_Accept(ctx); } } #ifdef HITLS_TLS_FEATURE_KEY_UPDATE /* The updateType types are as follows: HITLS_UPDATE_NOT_REQUESTED (0), HITLS_UPDATE_REQUESTED (1) or * HITLS_KEY_UPDATE_REQ_END(255). The local end sends 1 and the peer end sends 0 to the local end. The local end sends 0 * and the peer end does not send 0 to the local end. */ int32_t HITLS_KeyUpdate(HITLS_Ctx *ctx, uint32_t updateType) { if (ctx == NULL) { return HITLS_NULL_INPUT; } // Check whether the version is TLS1.3, whether the current status is transporting, and whether update is allowed. int32_t ret = HS_CheckKeyUpdateState(ctx, updateType); if (ret != HITLS_SUCCESS) { return ret; } ctx->keyUpdateType = updateType; ctx->isKeyUpdateRequest = true; ret = HS_Init(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15955, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "HS_Init fail when start keyupdate.", 0, 0, 0, 0); return ret; } // Successfully sendKeyUpdate. Set isKeyUpdateRequest to false and keyUpdateType to HITLS_KEY_UPDATE_REQ_END. ChangeConnState(ctx, CM_STATE_HANDSHAKING); HS_ChangeState(ctx, TRY_SEND_KEY_UPDATE); return HITLS_SUCCESS; } int32_t HITLS_GetKeyUpdateType(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } if (ctx->isKeyUpdateRequest) { return (int32_t)ctx->keyUpdateType; } return HITLS_KEY_UPDATE_REQ_END; } #endif #ifdef HITLS_TLS_FEATURE_RENEGOTIATION static int32_t CheckRenegotiateValid(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } uint8_t isSupport = false; (void)HITLS_GetRenegotiationSupport(ctx, &isSupport); /* Renegotiation is disabled */ if (isSupport == false) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16071, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "forbid renegotiate.", 0, 0, 0, 0); return HITLS_CM_LINK_UNSUPPORT_SECURE_RENEGOTIATION; } /* If the version is TLS1.3 or the current link does not support security renegotiation, the system returns. */ if ((ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) || (!ctx->negotiatedInfo.isSecureRenegotiation)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15953, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "unsupported renegotiate.", 0, 0, 0, 0); return HITLS_CM_LINK_UNSUPPORT_SECURE_RENEGOTIATION; } /* If the link is not established, renegotiation cannot be performed. */ if ((ctx->state != CM_STATE_TRANSPORTING) && (ctx->state != CM_STATE_RENEGOTIATION)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15954, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "please complete the link establishment first.", 0, 0, 0, 0); return HITLS_CM_LINK_UNESTABLISHED; } return HITLS_SUCCESS; } int32_t HITLS_Renegotiate(HITLS_Ctx *ctx) { int32_t ret = CheckRenegotiateValid(ctx); if (ret != HITLS_SUCCESS) { return ret; } if (ctx->negotiatedInfo.isRenegotiation) { /* If the current state is renegotiation, no change is made. */ return HITLS_SUCCESS; } ctx->negotiatedInfo.isRenegotiation = true; /* Start renegotiation */ if (ctx->hsCtx != NULL) { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) /* The retransmission queue needs to be cleared in the dtls over UDP scenario. */ REC_RetransmitListClean(ctx->recCtx); #endif HS_DeInit(ctx); } ret = HS_Init(ctx); if (ret != HITLS_SUCCESS) { ctx->negotiatedInfo.isRenegotiation = false; /* renegotiation fails */ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15955, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "HS_Init fail when start renegotiate.", 0, 0, 0, 0); return ret; } ctx->userRenego = true; /* renegotiation initiated by the local end */ ctx->negotiatedInfo.renegotiationNum++; ChangeConnState(ctx, CM_STATE_RENEGOTIATION); return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_RENEGOTIATION */ #ifdef HITLS_TLS_FEATURE_PHA int32_t HITLS_VerifyClientPostHandshake(HITLS_Ctx *ctx) { if (ctx == NULL) { return HITLS_NULL_INPUT; } if (ctx->isClient) { return HITLS_INVALID_INPUT; } if (ctx->state != CM_STATE_TRANSPORTING || ctx->phaState != PHA_EXTENSION) { return HITLS_MSG_HANDLE_STATE_ILLEGAL; } ctx->phaState = PHA_PENDING; return HITLS_SUCCESS; } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_establish.c
C
unknown
25,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. */ #include <stdbool.h> #include "hitls_build.h" #include "hitls_error.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "hitls_type.h" #include "rec.h" #include "hs.h" #include "app.h" #include "alert.h" #include "change_cipher_spec.h" #include "conn_common.h" #include "hs_ctx.h" // an instance of unexpectedMsgProcessCb int32_t ConnUnexpectedMsg(HITLS_Ctx *ctx, uint32_t msgType, const uint8_t *data, uint32_t dataLen, bool isPlain) { (void)isPlain; if (ctx == NULL || data == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16509, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } if (msgType != REC_TYPE_ALERT) { ALERT_ClearWarnCount(ctx); } int32_t ret = HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; #ifdef HITLS_TLS_PROTO_TLS13 if (isPlain) { // tls13 if (msgType == REC_TYPE_CHANGE_CIPHER_SPEC) { return ProcessPlainCCS(ctx, data, dataLen); } return ProcessPlainAlert(ctx, data, dataLen); } #endif switch (msgType) { case REC_TYPE_CHANGE_CIPHER_SPEC: return ProcessDecryptedCCS(ctx, data, dataLen); case REC_TYPE_ALERT: return ProcessDecryptedAlert(ctx, data, dataLen); default: BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16512, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "unknown msgType", 0, 0, 0, 0); ALERT_Send(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); break; } return ret; } int32_t CONN_Init(TLS_Ctx *ctx) { int32_t ret = REC_Init(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = ALERT_Init(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = CCS_Init(ctx); if (ret != HITLS_SUCCESS) { return ret; } ret = HS_Init(ctx); if (ret != HITLS_SUCCESS) { return ret; } ctx->method.isRecvCCS = CCS_IsRecv; ctx->method.sendCCS = CCS_Send; ctx->method.ctrlCCS = CCS_Ctrl; ctx->method.sendAlert = ALERT_Send; ctx->method.getAlertFlag = ALERT_GetFlag; ctx->method.unexpectedMsgProcessCb = ConnUnexpectedMsg; #ifdef HITLS_TLS_FEATURE_KEY_UPDATE ctx->keyUpdateType = HITLS_KEY_UPDATE_REQ_END; ctx->isKeyUpdateRequest = false; #endif // default value is X509_V_OK(0) ctx->peerInfo.verifyResult = 0; #ifdef HITLS_TLS_CONFIG_STATE ctx->rwstate = HITLS_NOTHING; #endif return HITLS_SUCCESS; } void CONN_Deinit(TLS_Ctx *ctx) { REC_DeInit(ctx); ALERT_Deinit(ctx); CCS_DeInit(ctx); HS_DeInit(ctx); return; }
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_init.c
C
unknown
3,199
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_error.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "hitls_type.h" #include "tls.h" #include "rec.h" #include "alert.h" #include "app.h" #include "conn_common.h" #include "hs.h" #include "hs_msg.h" #include "hs_common.h" #include "hs_ctx.h" #include "crypt.h" #include "hs_state_recv.h" #include "bsl_bytes.h" #include "hs_dtls_timer.h" #define HS_MESSAGE_LEN_FIELD 3u #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) // The HITLS protocol specifies the specification for the maximum timeout period, 3600 seconds. #define DTLS_SPECIFY_MAX_TIMEOUT_VALUE 3600 #endif static int32_t ReadEventInIdleState(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { (void)ctx; (void)data; (void)bufSize; (void)readLen; return HITLS_CM_LINK_UNESTABLISHED; } int32_t RecvUnexpectMsgInTransportingStateProcess(HITLS_Ctx *ctx) { if (ctx->state == CM_STATE_HANDSHAKING) { return CommonEventInHandshakingState(ctx); } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION if (ctx->state == CM_STATE_RENEGOTIATION) { int32_t ret = CommonEventInRenegotiationState(ctx); if (ret == HITLS_SUCCESS) { /* The renegotiation initiated by the peer is processed and returned. */ return ret; } if (ret != HITLS_REC_NORMAL_RECV_UNEXPECT_MSG) { /* If an error is returned during renegotiation, the error code must be sent to the user */ return ret; } if (ctx->state == CM_STATE_ALERTED) { /* If the alert message has been processed, the link must be disconnected */ return ret; } } #endif return HITLS_SUCCESS; } static int32_t RecvRenegoReqPreprocess(TLS_Ctx *ctx, uint8_t type) { /* If the version is TLS1.3, ignore the message */ if (ctx->negotiatedInfo.version == HITLS_VERSION_TLS13) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16514, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "tls13 not support Renegotiation", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } /* If the message is not a renegotiation request, ignore the message */ if ((ctx->isClient && (type == CLIENT_HELLO)) || (!ctx->isClient && (type == HELLO_REQUEST))) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16515, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ignore the message", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } /* if client renegotiate is not allowed, send no renegotiate alert, change state to CM_STATE_HANDSHAKING to finish this process */ if (type == CLIENT_HELLO && !ctx->config.tlsConfig.allowClientRenegotiate && !ctx->userRenego) { ChangeConnState(ctx, CM_STATE_HANDSHAKING); (void)HS_ChangeState(ctx, TRY_RECV_CLIENT_HELLO); return HITLS_SUCCESS; } /* Renegotiation request is processed only after security renegotiation is negotiated. Otherwise, no renegotiation * alert is generated and the peer determines whether to disconnect the link */ if (!ctx->negotiatedInfo.isSecureRenegotiation || !ctx->config.tlsConfig.isSupportRenegotiation) { if (type == HELLO_REQUEST) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16516, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "not support Renegotiation", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_WARNING, ALERT_NO_RENEGOTIATION); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } else { ChangeConnState(ctx, CM_STATE_HANDSHAKING); (void)HS_ChangeState(ctx, TRY_RECV_CLIENT_HELLO); return HITLS_SUCCESS; } } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) REC_RetransmitListClean(ctx->recCtx); /* dtls over udp scenario, the retransmission queue needs to be cleared */ #endif ChangeConnState(ctx, CM_STATE_RENEGOTIATION); if (type == CLIENT_HELLO) { // When the server start renegotiation, it sends a hello request message first, and the value of // nextSendSeq increases to 1. Then, the hsctx is released and the nextSendSeq is reset to 0. // Therefore, the value of nextSendSeq should return to 1 when sending server hello. #ifdef HITLS_TLS_PROTO_DTLS12 if (ctx->userRenego && IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { ctx->hsCtx->nextSendSeq++; } #endif (void)HS_ChangeState(ctx, TRY_RECV_CLIENT_HELLO); } else { (void)HS_ChangeState(ctx, TRY_RECV_HELLO_REQUEST); } return HITLS_SUCCESS; } static int32_t RecvKeyUpdatePreprocess(TLS_Ctx *ctx) { if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16517, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "negotiatedInfo version is not tls13", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } ChangeConnState(ctx, CM_STATE_HANDSHAKING); return HS_ChangeState(ctx, TRY_RECV_KEY_UPDATE); } static int32_t RecvCertReqPreprocess(TLS_Ctx *ctx) { if (ctx->state != CM_STATE_TRANSPORTING || ctx->phaState != PHA_EXTENSION || !ctx->isClient || ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16518, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ctx state err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; }; SAL_CRYPT_DigestFree(ctx->hsCtx->verifyCtx->hashCtx); ctx->hsCtx->verifyCtx->hashCtx = SAL_CRYPT_DigestCopy(ctx->phaHash); if (ctx->hsCtx->verifyCtx->hashCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16178, 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; } ctx->phaState = PHA_REQUESTED; ChangeConnState(ctx, CM_STATE_HANDSHAKING); return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE_REQUEST); } static int32_t RecvCertPreprocess(TLS_Ctx *ctx) { if (ctx->state != CM_STATE_TRANSPORTING || ctx->phaState != PHA_REQUESTED || ctx->isClient || ctx->negotiatedInfo.version != HITLS_VERSION_TLS13) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16519, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ctx state err", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } SAL_CRYPT_DigestFree(ctx->hsCtx->verifyCtx->hashCtx); ctx->hsCtx->verifyCtx->hashCtx = ctx->phaCurHash; ctx->phaCurHash = NULL; ChangeConnState(ctx, CM_STATE_HANDSHAKING); return HS_ChangeState(ctx, TRY_RECV_CERTIFICATE); } static int32_t RecvNSTPreprocess(TLS_Ctx *ctx) { if (ctx->negotiatedInfo.version != HITLS_VERSION_TLS13 || ctx->isClient == false) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16520, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "version err or it is server", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } ChangeConnState(ctx, CM_STATE_HANDSHAKING); return HS_ChangeState(ctx, TRY_RECV_NEW_SESSION_TICKET); } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static int32_t RecvPostFinishPreprocess(TLS_Ctx *ctx) { if (!IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask)) { BSL_LOG_BINLOG_VARLEN(BINLOG_ID16131, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Unexpected %s handshake state message.", HS_GetMsgTypeStr(ctx->hsCtx->msgBuf[0])); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } bool isTimeout = false; if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16521, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "GetUioChainTransportType fail", 0, 0, 0, 0); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } if (HS_IsTimeout(ctx, &isTimeout) != HITLS_SUCCESS || isTimeout) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16522, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HS_IsTimeout fail or timeout", 0, 0, 0, 0); REC_RetransmitListClean(ctx->recCtx); HS_DeInit(ctx); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } if ((ctx->isClient && !ctx->negotiatedInfo.isResume) || (!ctx->isClient && ctx->negotiatedInfo.isResume)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16523, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "RecvPostFinishPreprocess fail", 0, 0, 0, 0); return HITLS_REC_NORMAL_RECV_UNEXPECT_MSG; } ChangeConnState(ctx, CM_STATE_HANDSHAKING); return HS_ChangeState(ctx, TRY_RECV_FINISH); } #endif static int32_t PreprocessUnexpectHsMsg(HITLS_Ctx *ctx) { if (ctx->hsCtx != NULL) { HS_DeInit(ctx); } int32_t ret = HS_Init(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15977, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HS_Init fail when receive unexpected handshake message.", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } // get the handshake message type ret = ReadHsMessage(ctx, 1); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16524, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ReadHsMessage fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_INTERNAL_ERROR); return ret; } HS_Ctx *hsCtx = ctx->hsCtx; switch (hsCtx->msgBuf[0]) { case HELLO_REQUEST: case CLIENT_HELLO: ret = RecvRenegoReqPreprocess(ctx, hsCtx->msgBuf[0]); break; case KEY_UPDATE: ret = RecvKeyUpdatePreprocess(ctx); break; case CERTIFICATE_REQUEST: ret = RecvCertReqPreprocess(ctx); break; case CERTIFICATE: ret = RecvCertPreprocess(ctx); break; case NEW_SESSION_TICKET: ret = RecvNSTPreprocess(ctx); break; #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) case FINISHED: ret = RecvPostFinishPreprocess(ctx); break; #endif default: BSL_LOG_BINLOG_VARLEN(BINLOG_ID16529, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Unexpected %s handshake state message.", HS_GetMsgTypeStr(hsCtx->msgBuf[0])); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); ret = HITLS_MSG_HANDLE_UNEXPECTED_MESSAGE; } return ret; } static void ConsumeHandshakeMessage(HITLS_Ctx *ctx) { bool isDtls = IS_SUPPORT_DATAGRAM(ctx->config.tlsConfig.originVersionMask); uint32_t headerLen = isDtls ? DTLS_HS_MSG_HEADER_SIZE : HS_MSG_HEADER_SIZE; int32_t ret = ReadHsMessage(ctx, headerLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16525, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ReadHsMessage fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return; } uint32_t length = BSL_ByteToUint24(&ctx->hsCtx->msgBuf[headerLen - HS_MESSAGE_LEN_FIELD]); ret = ReadHsMessage(ctx, length + headerLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16526, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ReadHsMessage fail", 0, 0, 0, 0); ctx->method.sendAlert(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); return; } } static int32_t ReadEventInTransportingState(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { int32_t ret = 0; int32_t unexpectMsgRet = 0; do { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) /* In UDP scenarios, the 2MSL timer expires */ ret = HS_CheckAndProcess2MslTimeout(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif ret = APP_Read(ctx, data, bufSize, readLen); if (ret == HITLS_SUCCESS) { if ((!ctx->negotiatedInfo.isRenegotiation) && (ctx->hsCtx != NULL)) { HS_DeInit(ctx); } /* An APP message is received */ break; } if (ret == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG && REC_GetUnexpectedMsgType(ctx) == REC_TYPE_HANDSHAKE) { unexpectMsgRet = PreprocessUnexpectHsMsg(ctx); if (unexpectMsgRet != HITLS_SUCCESS) { ConsumeHandshakeMessage(ctx); HS_DeInit(ctx); ret = unexpectMsgRet; } } if (ALERT_GetFlag(ctx)) { #ifdef HITLS_TLS_FEATURE_RENEGOTIATION /* After the server sends a hello request, the status changes to transporting. In this case, the read command is used to read the message. If the no_renegotiation alert is received, the connection needs to be disconnected. */ if (ctx->userRenego) { InnerRenegotiationProcess(ctx); } #endif if (ALERT_HaveExceeded(ctx, MAX_ALERT_COUNT)) { /* If multiple consecutive alerts exist, the link is abnormal and needs to be disconnected */ ALERT_Send(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } unexpectMsgRet = AlertEventProcess(ctx); if (unexpectMsgRet != HITLS_SUCCESS) { /* If the alert fails to be sent, a response is returned to the user for processing */ return unexpectMsgRet; } /* If fatal alert or close_notify has been processed, the link must be disconnected */ if (ctx->state == CM_STATE_ALERTED || ctx->state == CM_STATE_CLOSED) { return ret; } } if (ret != HITLS_REC_NORMAL_RECV_UNEXPECT_MSG) { return ret; } unexpectMsgRet = RecvUnexpectMsgInTransportingStateProcess(ctx); if (unexpectMsgRet != HITLS_SUCCESS) { return unexpectMsgRet; } #ifdef HITLS_TLS_FEATURE_MODE_AUTO_RETRY if ((ctx->config.tlsConfig.modeSupport & HITLS_MODE_AUTO_RETRY) == 0) { return HITLS_REC_NORMAL_RECV_BUF_EMPTY; } #endif } while (ret != HITLS_SUCCESS); return ret; } static int32_t ReadEventInHandshakingState(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { int32_t ret = CommonEventInHandshakingState(ctx); if (ret != HITLS_SUCCESS) { return ret; } return ReadEventInTransportingState(ctx, data, bufSize, readLen); } static int32_t ReadEventInRenegotiationState(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t ret = CommonEventInRenegotiationState(ctx); if (ret != HITLS_SUCCESS) { if (ret != HITLS_REC_NORMAL_RECV_UNEXPECT_MSG || ctx->state == CM_STATE_ALERTED) { /* If an error is returned during the renegotiation, the error code must be sent to the user */ return ret; } /* The scenario is that the HITLS initiates renegotiation, but the peer end does not respond with a handshake * message and continues to send the app message. In this case, you need to read the app message to prevent * message blocking. */ ret = APP_Read(ctx, data, bufSize, readLen); return ret; } return ReadEventInTransportingState(ctx, data, bufSize, readLen); #else (void)ctx; (void)data; (void)bufSize; (void)readLen; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15407, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "invalid conn states %d", CM_STATE_RENEGOTIATION, NULL, NULL, NULL); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t ReadEventInAlertedState(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { (void)ctx; (void)data; (void)bufSize; (void)readLen; // A message indicating that the link status is abnormal is displayed. return HITLS_CM_LINK_FATAL_ALERTED; } static int32_t ReadEventInClosedState(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { // Non-closed state if ((ctx->shutdownState & HITLS_RECEIVED_SHUTDOWN) == 0) { ALERT_CleanInfo(ctx); int32_t ret = APP_Read(ctx, data, bufSize, readLen); if (ret == HITLS_SUCCESS) { return HITLS_SUCCESS; } // There is no alert message to be processed. if (ALERT_GetFlag(ctx) == false) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16531, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Read fail", 0, 0, 0, 0); return ret; } int32_t alertRet = AlertEventProcess(ctx); if (alertRet != HITLS_SUCCESS) { return alertRet; } /* Other warning alerts have been processed. */ if ((ctx->shutdownState & HITLS_RECEIVED_SHUTDOWN) == 0) { return ret; } } // Directly return to link closed. return HITLS_CM_LINK_CLOSED; } static int32_t ReadProcess(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { ReadEventProcess readEventProcess[CM_STATE_END] = { ReadEventInIdleState, ReadEventInHandshakingState, ReadEventInTransportingState, ReadEventInRenegotiationState, NULL, ReadEventInAlertedState, ReadEventInClosedState }; if ((GetConnState(ctx) >= CM_STATE_END) || (GetConnState(ctx) == CM_STATE_ALERTING)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16532, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); /* If the alert message is sent successfully, the system switches to another state. Otherwise, an internal * exception occurs */ return HITLS_INTERNAL_EXCEPTION; } ReadEventProcess proc = readEventProcess[GetConnState(ctx)]; return proc(ctx, data, bufSize, readLen); } int32_t HITLS_Read(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { int32_t ret; if (ctx == NULL || data == NULL || readLen == NULL) { return HITLS_NULL_INPUT; } ctx->allowAppOut = true; /* Process the unsent alert message first, and then enter the corresponding state processing function based on the * processing result */ if (GetConnState(ctx) == CM_STATE_ALERTING) { ret = CommonEventInAlertingState(ctx); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16533, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Alerting fail", 0, 0, 0, 0); /* If the alert message fails to be sent, the system returns the message to the user for processing */ return ret; } } return ReadProcess(ctx, data, bufSize, readLen); } int32_t HITLS_Peek(HITLS_Ctx *ctx, uint8_t *data, uint32_t bufSize, uint32_t *readLen) { if (ctx == NULL) { return HITLS_NULL_INPUT; } ctx->peekFlag = 1; int32_t ret = HITLS_Read(ctx, data, bufSize, readLen); ctx->peekFlag = 0; return ret; } int32_t HITLS_ReadHasPending(const HITLS_Ctx *ctx, uint8_t *isPending) { if (ctx == NULL || isPending == NULL) { return HITLS_NULL_INPUT; } *isPending = APP_GetReadPendingBytes(ctx) > 0 || REC_ReadHasPending(ctx) ? 1 : 0; return HITLS_SUCCESS; } uint32_t HITLS_GetReadPendingBytes(const HITLS_Ctx *ctx) { return APP_GetReadPendingBytes(ctx); } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HITLS_DtlsProcessTimeout(HITLS_Ctx *ctx) { if (ctx == NULL || ctx->hsCtx == NULL) { return HITLS_NULL_INPUT; } bool isTimeout = false; int32_t ret = HS_IsTimeout(ctx, &isTimeout); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17032, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "HS_IsTimeout fail", 0, 0, 0, 0); return ret; } if (isTimeout) { ret = HS_TimeoutProcess(ctx); if (ret != HITLS_SUCCESS) { return ret; } /* Receive the message of the last flight when the receiving times out */ ret = REC_RetransmitListFlush(ctx); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_SUCCESS; } return HITLS_MSG_HANDLE_DTLS_RETRANSMIT_NOT_TIMEOUT; } int32_t HITLS_DtlsGetTimeout(HITLS_Ctx *ctx, uint64_t *remainTimeOut) { if (ctx == NULL || ctx->hsCtx == NULL || remainTimeOut == NULL) { return HITLS_NULL_INPUT; } *remainTimeOut = 0; if (!BSL_UIO_GetUioChainTransportType(ctx->uio, BSL_UIO_UDP) || ctx->hsCtx->timeoutValue == 0) { return HITLS_MSG_HANDLE_ERR_WITHOUT_TIMEOUT_ACTION; } BSL_TIME curTime; int32_t ret = BSL_SAL_SysTimeGet(&curTime); if (ret != BSL_SUCCESS) { return ret; } BSL_TIME endTime = ctx->hsCtx->deadline; ret = BSL_SAL_DateTimeCompareByUs(&curTime, &endTime); if (ret == BSL_TIME_DATE_AFTER || ret == BSL_TIME_CMP_EQUAL) { return HITLS_SUCCESS; } else if (ret == BSL_TIME_CMP_ERROR) { return BSL_TIME_CMP_ERROR; } int64_t curUtcTime = 0; int64_t endUtcTime = 0; /* Convert the date into seconds. */ ret = BSL_SAL_DateToUtcTimeConvert(&curTime, &curUtcTime); if (ret != BSL_SUCCESS) { return ret; } ret = BSL_SAL_DateToUtcTimeConvert(&endTime, &endUtcTime); if (ret != BSL_SUCCESS) { return ret; } uint64_t remainSecTimeout = (uint64_t)(endUtcTime - curUtcTime); if (remainSecTimeout >= DTLS_SPECIFY_MAX_TIMEOUT_VALUE) { *remainTimeOut = DTLS_SPECIFY_MAX_TIMEOUT_VALUE * BSL_SECOND_TRANSFER_RATIO * BSL_SECOND_TRANSFER_RATIO; return HITLS_SUCCESS; } uint64_t endMicroSec = endTime.millSec * BSL_SECOND_TRANSFER_RATIO + endTime.microSec; uint64_t curMicroSec = curTime.millSec * BSL_SECOND_TRANSFER_RATIO + curTime.microSec; *remainTimeOut = remainSecTimeout * BSL_SECOND_TRANSFER_RATIO * BSL_SECOND_TRANSFER_RATIO + endMicroSec - curMicroSec; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_DTLS12 && HITLS_BSL_UIO_UDP */
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_read.c
C
unknown
23,329
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_log_internal.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_log.h" #include "hitls_error.h" #include "hitls_type.h" #include "tls.h" #include "alert.h" #include "app.h" #include "conn_common.h" #include "hs.h" #include "hs_ctx.h" #include "record.h" int32_t HITLS_GetMaxWriteSize(const HITLS_Ctx *ctx, uint32_t *len) { if (ctx == NULL || len == NULL) { return HITLS_NULL_INPUT; } return APP_GetMaxWriteSize(ctx, len); } static int32_t WriteEventInIdleState(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { (void)ctx; (void)data; (void)dataLen; (void)writeLen; return HITLS_CM_LINK_UNESTABLISHED; } static int32_t WriteEventInTransportingState(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { int32_t ret; int32_t alertRet; do { #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) /* In UDP scenarios, the 2MSL timer expires */ ret = HS_CheckAndProcess2MslTimeout(ctx); if (ret != HITLS_SUCCESS) { return ret; } #endif ret = APP_Write(ctx, data, dataLen, writeLen); if (ret == HITLS_SUCCESS) { /* The message is sent successfully */ break; } if (!ALERT_GetFlag(ctx)) { /* Failed to send a message but no alert is displayed */ break; } if (ALERT_HaveExceeded(ctx, MAX_ALERT_COUNT)) { /* If multiple consecutive alerts exist, the link is abnormal and needs to be disconnected */ ALERT_Send(ctx, ALERT_LEVEL_FATAL, ALERT_UNEXPECTED_MESSAGE); } alertRet = AlertEventProcess(ctx); if (alertRet != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16546, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "AlertEventProcess fail", 0, 0, 0, 0); /* If the alert fails to be sent, a response is returned to the user */ return alertRet; } /* If fatal alert or close_notify has been processed, the link must be disconnected. */ if (ctx->state == CM_STATE_ALERTED) { break; } } while (ret != HITLS_SUCCESS); return ret; } static int32_t WriteEventInHandshakingState(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { // The link is being established. Therefore, the link establishment is triggered first. If the link is successfully // established, the message is directly sent. int32_t ret = CommonEventInHandshakingState(ctx); if (ret != HITLS_SUCCESS) { return ret; } return WriteEventInTransportingState(ctx, data, dataLen, writeLen); } static int32_t WriteEventInRenegotiationState(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t ret; if (ctx->recCtx->pendingData != NULL) { // Send the app data first. return WriteEventInTransportingState(ctx, data, dataLen, writeLen); } do { /* If an unexpected message is received, the system ignores the return value and continues to establish a link. * Otherwise, the system returns the return value to the user for processing */ ret = CommonEventInRenegotiationState(ctx); } while (ret == HITLS_REC_NORMAL_RECV_UNEXPECT_MSG && ctx->state != CM_STATE_ALERTED); if (ret != HITLS_SUCCESS) { if (ctx->negotiatedInfo.isRenegotiation || (ret != HITLS_REC_NORMAL_RECV_BUF_EMPTY)) { /* If an error is returned during renegotiation, the error code must be sent to the user */ return ret; } /* The scenario is that the HITLS server initiates renegotiation, but the peer end does not respond with the * client hello message. In this case,the app message needs to be sent to the peer end to prevent message * blocking */ } return WriteEventInTransportingState(ctx, data, dataLen, writeLen); #else (void)ctx; (void)data; (void)dataLen; (void)writeLen; BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15583, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "invalid conn states %d", CM_STATE_RENEGOTIATION, NULL, NULL, NULL); return HITLS_INTERNAL_EXCEPTION; #endif } static int32_t WriteEventInAlertedState(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { (void)ctx; (void)data; (void)dataLen; (void)writeLen; // Directly return a message indicating that the link status is abnormal. return HITLS_CM_LINK_FATAL_ALERTED; } static int32_t WriteEventInClosedState(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { if ((ctx->shutdownState & HITLS_SENT_SHUTDOWN) == 0) { ALERT_CleanInfo(ctx); int ret = APP_Write(ctx, data, dataLen, writeLen); if (ret == HITLS_SUCCESS || ret == HITLS_REC_NORMAL_IO_BUSY) { return ret; } // There is no alert message to be processed. if (ALERT_GetFlag(ctx) == false) { return ret; } int32_t alertRet = AlertEventProcess(ctx); if (alertRet != HITLS_SUCCESS) { return alertRet; } return ret; } // Directly return a message indicating that the link status is abnormal. return HITLS_CM_LINK_CLOSED; } #ifdef HITLS_TLS_FEATURE_PHA int32_t CommonCheckPostHandshakeAuth(TLS_Ctx *ctx) { if (!ctx->isClient && ctx->phaState == PHA_PENDING && ctx->state == CM_STATE_TRANSPORTING) { ChangeConnState(ctx, CM_STATE_HANDSHAKING); return HS_CheckPostHandshakeAuth(ctx); } return HITLS_SUCCESS; } #endif static int32_t HITLS_WritePreporcess(HITLS_Ctx *ctx) { int32_t ret = HITLS_SUCCESS; /* Process the unsent alert message first, and then enter the corresponding state processing function based on the * processing result */ if (GetConnState(ctx) == CM_STATE_ALERTING) { ret = CommonEventInAlertingState(ctx); if (ret != HITLS_SUCCESS) { /* If the alert message fails to be sent, the system returns the message to the user for processing */ return ret; } } #ifdef HITLS_TLS_FEATURE_PHA return CommonCheckPostHandshakeAuth(ctx); #else return ret; #endif } int32_t HITLS_Write(HITLS_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t *writeLen) { if (ctx == NULL || data == NULL || dataLen == 0 || writeLen == NULL) { return HITLS_NULL_INPUT; } ctx->allowAppOut = false; int32_t ret = HITLS_WritePreporcess(ctx); if (ret != HITLS_SUCCESS) { return ret; } WriteEventProcess writeEventProcess[CM_STATE_END] = { WriteEventInIdleState, WriteEventInHandshakingState, WriteEventInTransportingState, WriteEventInRenegotiationState, NULL, WriteEventInAlertedState, WriteEventInClosedState }; if ((GetConnState(ctx) >= CM_STATE_END) || (GetConnState(ctx) == CM_STATE_ALERTING)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16548, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "internal exception occurs", 0, 0, 0, 0); /* If the alert message is sent successfully, the system switches to another state. Otherwise, an internal * exception occurs */ return HITLS_INTERNAL_EXCEPTION; } WriteEventProcess proc = writeEventProcess[GetConnState(ctx)]; ret = proc(ctx, data, dataLen, writeLen); if (ret != HITLS_SUCCESS) { *writeLen = 0; } return ret; }
2302_82127028/openHiTLS-examples_5062_4009
tls/cm/src/conn_write.c
C
unknown
8,203
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CONFIG_H #define CONFIG_H #include <stdint.h> #include "bsl_log_internal.h" #include "bsl_binlog_id.h" #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif #define PROCESS_PARAM_INT32(tmpParam, paramObj, params, paramName, destField) \ do { \ (tmpParam) = BSL_PARAM_FindParam((BSL_Param *)(uintptr_t)(params), (paramName)); \ if ((tmpParam) == NULL || (tmpParam)->valueType != BSL_PARAM_TYPE_INT32) { \ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05075, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, \ "tls config: not found int32 param %s", #paramName, 0, 0, 0); \ goto ERR; \ } \ (paramObj)->destField = *(int32_t *)(tmpParam)->value; \ } while (0) #define PROCESS_PARAM_UINT16(tmpParam, paramObj, params, paramName, destField) \ do { \ (tmpParam) = BSL_PARAM_FindParam((BSL_Param *)(uintptr_t)(params), (paramName)); \ if ((tmpParam) == NULL || (tmpParam)->valueType != BSL_PARAM_TYPE_UINT16) { \ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05076, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, \ "tls config: not found uint16 param %s", #paramName, 0, 0, 0); \ goto ERR; \ } \ (paramObj)->destField = *(uint16_t *)(tmpParam)->value; \ } while (0) #define PROCESS_PARAM_UINT32(tmpParam, paramObj, params, paramName, destField) \ do { \ (tmpParam) = BSL_PARAM_FindParam((BSL_Param *)(uintptr_t)(params), (paramName)); \ if ((tmpParam) == NULL || (tmpParam)->valueType != BSL_PARAM_TYPE_UINT32) { \ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05077, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, \ "tls config: not found uint32 param %s", #paramName, 0, 0, 0); \ goto ERR; \ } \ (paramObj)->destField = *(uint32_t *)(tmpParam)->value; \ } while (0) #define PROCESS_PARAM_BOOL(tmpParam, paramObj, params, paramName, destField) \ do { \ (tmpParam) = BSL_PARAM_FindParam((BSL_Param *)(uintptr_t)(params), (paramName)); \ if ((tmpParam) == NULL || (tmpParam)->valueType != BSL_PARAM_TYPE_BOOL) { \ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05078, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, \ "tls config: not found bool param %s", #paramName, 0, 0, 0); \ goto ERR; \ } \ (paramObj)->destField = *(bool *)(tmpParam)->value; \ } while (0) #define PROCESS_STRING_PARAM(tmpParam, paramObj, params, paramName, destField) \ do { \ (tmpParam) = BSL_PARAM_FindParam((BSL_Param *)(uintptr_t)(params), (paramName)); \ if ((tmpParam) == NULL || (tmpParam)->valueType != BSL_PARAM_TYPE_OCTETS_PTR) { \ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05079, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, \ "tls config: not found string param %s", #paramName, 0, 0, 0); \ goto ERR; \ } \ (paramObj)->destField = BSL_SAL_Calloc((tmpParam)->valueLen + 1, sizeof(char)); \ if ((paramObj)->destField == NULL) { \ goto ERR; \ } \ (void)memcpy_s((paramObj)->destField, (tmpParam)->valueLen + 1, (tmpParam)->value, (tmpParam)->valueLen); \ } while (0) #define PROCESS_OPTIONAL_STRING_PARAM(tmpParam, params, paramName, outString, outStringLen, nameParamName, outName) \ do { \ (tmpParam) = BSL_PARAM_FindParam((BSL_Param *)(uintptr_t)(params), (paramName)); \ if ((tmpParam) == NULL) { \ (outString) = NULL; \ } else if ((tmpParam)->valueType == BSL_PARAM_TYPE_OCTETS_PTR) { \ (outString) = (const char *)(tmpParam)->value; \ (outStringLen) = (tmpParam)->valueLen; \ (tmpParam) = BSL_PARAM_FindParam((BSL_Param *)(uintptr_t)(params), (nameParamName)); \ if ((tmpParam) == NULL || (tmpParam)->valueType != BSL_PARAM_TYPE_OCTETS_PTR) { \ BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05080, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, \ "tls config: not found optional string param %s", #nameParamName, 0, 0, 0); \ goto ERR; \ } \ (outName) = (const char *)(tmpParam)->value; \ } else { \ goto ERR; \ } \ } while (0) /** clear the TLS configuration */ void CFG_CleanConfig(HITLS_Config *config); /** copy the TLS configuration */ int32_t DumpConfig(HITLS_Ctx *ctx, const HITLS_Config *srcConfig); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/config/include/config.h
C
unknown
4,997
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CONFIG_CHECK_H #define CONFIG_CHECK_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif /** check the version */ int32_t CheckVersion(uint16_t minVersion, uint16_t maxVersion); /** check whether the TLS configuration is valid */ int32_t CheckConfig(const HITLS_Config *config); uint32_t MapVersion2VersionBit(bool isDatagram, uint16_t version); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/config/include/config_check.h
C
unknown
971
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CONFIG_TYPE_H #define CONFIG_TYPE_H #include <stdint.h> #include "hitls_type.h" #include "tls_config.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Load group information * @param config: config context * @return HITLS_SUCCESS: success, other: error */ int32_t ConfigLoadGroupInfo(HITLS_Config *config); /** * @brief Get group information * @param config: config context * @param groupId: group id * @return group information */ const TLS_GroupInfo *ConfigGetGroupInfo(const HITLS_Config *config, uint16_t groupId); /** * @brief Get group information list * @param config: config context * @param size: size of group information list * @return group information list */ const TLS_GroupInfo *ConfigGetGroupInfoList(const HITLS_Config *config, uint32_t *size); /** * @brief Load signature scheme information * @param config: config context * @return HITLS_SUCCESS: success, other: error */ int32_t ConfigLoadSignatureSchemeInfo(HITLS_Config *config); /** * @brief Get signature scheme information * @param config: config context * @param signatureScheme: signature scheme * @return signature scheme information */ const TLS_SigSchemeInfo *ConfigGetSignatureSchemeInfo(const HITLS_Config *config, uint16_t signatureScheme); /** * @brief Get signature scheme information list * @param config: config context * @param size: size of signature scheme information list * @return signature scheme information list */ const TLS_SigSchemeInfo *ConfigGetSignatureSchemeInfoList(const HITLS_Config *config, uint32_t *size); #ifdef __cplusplus } #endif #endif /* CONFIG_TYPE_H */
2302_82127028/openHiTLS-examples_5062_4009
tls/config/include/config_type.h
C
unknown
2,163
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "tls.h" #include "tls_config.h" #include "cipher_suite.h" #include "config_type.h" #ifndef HITLS_TLS_CONFIG_CIPHER_SUITE #define CIPHER_NAME(name) NULL #else #define CIPHER_NAME(name) name #endif #define KEY_BLOCK_PARTITON_LENGTH(fixedIvLth, encKeyLth, macKeyLth, blockLth, recordIvLth, macLth) \ .fixedIvLength = (fixedIvLth), \ .encKeyLen = (encKeyLth), \ .macKeyLen = (macKeyLth), \ .blockLength = (blockLth), \ .recordIvLength = (recordIvLth), \ .macLen = (macLth) \ #define VERSION_SCOPE(minV, maxV, minDtlsV, maxDtlsV) \ .minVersion = (minV), \ .maxVersion = (maxV), \ .minDtlsVersion = (minDtlsV), \ .maxDtlsVersion = (maxDtlsV) #ifdef HITLS_TLS_CONFIG_CIPHER_SUITE #define CIPHERSUITE_DESCRIPTION_MAXLEN 128 #endif /* If cipher suites need to be added in the future, you need to consider whether the cipher suites are suitable for DTLS in terms of design. If DTLS is not supported, perform related operations. For example, the RC4 stream encryption algorithm is not applicable to DTLS. */ static const CipherSuiteInfo g_cipherSuiteList[] = { #ifdef HITLS_TLS_SUITE_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_AES_128_GCM_SHA256"), .cipherSuite = HITLS_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_NULL, .authAlg = HITLS_AUTH_ANY, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 16u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS13, HITLS_VERSION_TLS13, 0u, 0u), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_AES_256_GCM_SHA384"), .cipherSuite = HITLS_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_NULL, .authAlg = HITLS_AUTH_ANY, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS13, HITLS_VERSION_TLS13, 0u, 0u), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_NULL, .authAlg = HITLS_AUTH_ANY, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS13, HITLS_VERSION_TLS13, 0u, 0u), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_AES_128_CCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_AES_128_CCM_SHA256"), .stdName = CIPHER_NAME("TLS_AES_128_CCM_SHA256"), .cipherSuite = HITLS_AES_128_CCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CCM, .kxAlg = HITLS_KEY_EXCH_NULL, .authAlg = HITLS_AUTH_ANY, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 16u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS13, HITLS_VERSION_TLS13, 0u, 0u), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_AES_128_CCM_8_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_AES_128_CCM_8_SHA256"), .stdName = CIPHER_NAME("TLS_AES_128_CCM_8_SHA256"), .cipherSuite = HITLS_AES_128_CCM_8_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CCM8, .kxAlg = HITLS_KEY_EXCH_NULL, .authAlg = HITLS_AUTH_ANY, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 16u, 0u, 0u, 0u, 8u), VERSION_SCOPE(HITLS_VERSION_TLS13, HITLS_VERSION_TLS13, 0u, 0u), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_RSA_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_RSA_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_256_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_256_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_256_CBC_SHA256"), .cipherSuite = HITLS_RSA_WITH_AES_256_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_RSA_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_RSA_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_384, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 48u, 16u, 16u, 48u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_RSA_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_RSA_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_RSA_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_RSA_WITH_AES_256_CBC_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"), .stdName = CIPHER_NAME("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"), .cipherSuite = HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_384, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 48u, 16u, 16u, 48u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_RSA_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_RSA_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_DSS_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_DSS, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_DSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_DSS_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_DSS, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_DSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_DSS_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DHE_DSS_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DHE_DSS_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_DHE_DSS_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_DSS, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_DSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_DSS_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DHE_DSS_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DHE_DSS_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_DHE_DSS_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_DSS, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_DSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_DSS_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_DSS_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_DHE_DSS_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_DSS, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_DSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_DSS_WITH_AES_256_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_DSS_WITH_AES_256_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"), .cipherSuite = HITLS_DHE_DSS_WITH_AES_256_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_DSS, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_DSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_256_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif // psk nego #ifdef HITLS_TLS_SUITE_PSK_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_PSK_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_PSK_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_PSK_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_PSK_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_PSK_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_PSK_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_RSA_PSK_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_RSA_PSK_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_RSA_PSK_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_RSA_PSK, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_PSK_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_RSA_PSK_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_RSA_PSK_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_RSA_PSK_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_RSA_PSK, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_PSK_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_PSK_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_PSK_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_PSK_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_PSK_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_PSK_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_PSK_WITH_AES_256_CCM {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_AES_256_CCM"), .stdName = CIPHER_NAME("TLS_PSK_WITH_AES_256_CCM"), .cipherSuite = HITLS_PSK_WITH_AES_256_CCM, .cipherAlg = HITLS_CIPHER_AES_256_CCM, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_128_CCM {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_128_CCM"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_128_CCM"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_128_CCM, .cipherAlg = HITLS_CIPHER_AES_128_CCM, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_256_CCM {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_256_CCM"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_256_CCM"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_256_CCM, .cipherAlg = HITLS_CIPHER_AES_256_CCM, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_PSK_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_RSA_PSK, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_PSK_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_RSA_PSK, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_PSK_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_PSK_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_PSK_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_PSK_WITH_AES_256_CBC_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_AES_256_CBC_SHA384"), .stdName = CIPHER_NAME("TLS_PSK_WITH_AES_256_CBC_SHA384"), .cipherSuite = HITLS_PSK_WITH_AES_256_CBC_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_384, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 48u, 16u, 16u, 48u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_AES_256_CBC_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_AES_256_CBC_SHA384"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"), .cipherSuite = HITLS_DHE_PSK_WITH_AES_256_CBC_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_384, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 48u, 16u, 16u, 48u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_PSK_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_RSA_PSK, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_PSK_WITH_AES_256_CBC_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384"), .stdName = CIPHER_NAME("TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"), .cipherSuite = HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_RSA_PSK, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_384, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 48u, 16u, 16u, 48u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_AES_256_CBC_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"), .cipherSuite = HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_384, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 48u, 16u, 16u, 48u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_PSK_WITH_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_PSK_WITH_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_DHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256"), .stdName = CIPHER_NAME("TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256"), .cipherSuite = HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256, .cipherAlg = HITLS_CIPHER_CHACHA20_POLY1305, .kxAlg = HITLS_KEY_EXCH_RSA_PSK, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(12u, 32u, 0u, 0u, 0u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_AES_128_CCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256"), .cipherSuite = HITLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CCM, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_PSK_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_ECDHE_PSK, .authAlg = HITLS_AUTH_PSK, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif /* Anonymous cipher suites support */ #ifdef HITLS_TLS_SUITE_DH_ANON_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DH_ANON_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DH_anon_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_DH_ANON_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DH_ANON_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_DH_ANON_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_DH_anon_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_DH_ANON_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_SSL30, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DH_ANON_WITH_AES_128_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DH_ANON_WITH_AES_128_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_DH_anon_WITH_AES_128_CBC_SHA256"), .cipherSuite = HITLS_DH_ANON_WITH_AES_128_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DH_ANON_WITH_AES_256_CBC_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DH_ANON_WITH_AES_256_CBC_SHA256"), .stdName = CIPHER_NAME("TLS_DH_anon_WITH_AES_256_CBC_SHA256"), .cipherSuite = HITLS_DH_ANON_WITH_AES_256_CBC_SHA256, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_256, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DH_ANON_WITH_AES_128_GCM_SHA256 {.enable = true, .name = CIPHER_NAME("HITLS_DH_ANON_WITH_AES_128_GCM_SHA256"), .stdName = CIPHER_NAME("TLS_DH_anon_WITH_AES_128_GCM_SHA256"), .cipherSuite = HITLS_DH_ANON_WITH_AES_128_GCM_SHA256, .cipherAlg = HITLS_CIPHER_AES_128_GCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DH_ANON_WITH_AES_256_GCM_SHA384 {.enable = true, .name = CIPHER_NAME("HITLS_DH_ANON_WITH_AES_256_GCM_SHA384"), .stdName = CIPHER_NAME("TLS_DH_anon_WITH_AES_256_GCM_SHA384"), .cipherSuite = HITLS_DH_ANON_WITH_AES_256_GCM_SHA384, .cipherAlg = HITLS_CIPHER_AES_256_GCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_384, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDH_ANON_WITH_AES_128_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDH_ANON_WITH_AES_128_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDH_anon_WITH_AES_128_CBC_SHA"), .cipherSuite = HITLS_ECDH_ANON_WITH_AES_128_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_128_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDH_ANON_WITH_AES_256_CBC_SHA {.enable = true, .name = CIPHER_NAME("HITLS_ECDH_ANON_WITH_AES_256_CBC_SHA"), .stdName = CIPHER_NAME("TLS_ECDH_anon_WITH_AES_256_CBC_SHA"), .cipherSuite = HITLS_ECDH_ANON_WITH_AES_256_CBC_SHA, .cipherAlg = HITLS_CIPHER_AES_256_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_NULL, .macAlg = HITLS_MAC_1, .hashAlg = HITLS_HASH_SHA1, .signScheme = CERT_SIG_SCHEME_UNKNOWN, KEY_BLOCK_PARTITON_LENGTH(16u, 32u, 20u, 16u, 16u, 20u), VERSION_SCOPE(HITLS_VERSION_TLS10, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_128_CCM {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_128_CCM"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_128_CCM"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_128_CCM, .cipherAlg = HITLS_CIPHER_AES_128_CCM, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_ECDSA_WITH_AES_256_CCM {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_ECDSA_WITH_AES_256_CCM"), .stdName = CIPHER_NAME("TLS_ECDHE_ECDSA_WITH_AES_256_CCM"), .cipherSuite = HITLS_ECDHE_ECDSA_WITH_AES_256_CCM, .cipherAlg = HITLS_CIPHER_AES_256_CCM, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_ECDSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_ECDSA_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_128_CCM {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_128_CCM"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_128_CCM"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_128_CCM, .cipherAlg = HITLS_CIPHER_AES_128_CCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_DHE_RSA_WITH_AES_256_CCM {.enable = true, .name = CIPHER_NAME("HITLS_DHE_RSA_WITH_AES_256_CCM"), .stdName = CIPHER_NAME("TLS_DHE_RSA_WITH_AES_256_CCM"), .cipherSuite = HITLS_DHE_RSA_WITH_AES_256_CCM, .cipherAlg = HITLS_CIPHER_AES_256_CCM, .kxAlg = HITLS_KEY_EXCH_DHE, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_128_CCM {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_128_CCM"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_128_CCM"), .cipherSuite = HITLS_RSA_WITH_AES_128_CCM, .cipherAlg = HITLS_CIPHER_AES_128_CCM, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_128_CCM_8 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_128_CCM_8"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_128_CCM_8"), .cipherSuite = HITLS_RSA_WITH_AES_128_CCM_8, .cipherAlg = HITLS_CIPHER_AES_128_CCM8, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 8u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_256_CCM {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_256_CCM"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_256_CCM"), .cipherSuite = HITLS_RSA_WITH_AES_256_CCM, .cipherAlg = HITLS_CIPHER_AES_256_CCM, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_SUITE_RSA_WITH_AES_256_CCM_8 {.enable = true, .name = CIPHER_NAME("HITLS_RSA_WITH_AES_256_CCM_8"), .stdName = CIPHER_NAME("TLS_RSA_WITH_AES_256_CCM_8"), .cipherSuite = HITLS_RSA_WITH_AES_256_CCM_8, .cipherAlg = HITLS_CIPHER_AES_256_CCM8, .kxAlg = HITLS_KEY_EXCH_RSA, .authAlg = HITLS_AUTH_RSA, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SHA_256, .signScheme = CERT_SIG_SCHEME_RSA_PKCS1_SHA1, KEY_BLOCK_PARTITON_LENGTH(4u, 32u, 0u, 0u, 8u, 8u), VERSION_SCOPE(HITLS_VERSION_TLS12, HITLS_VERSION_TLS12, HITLS_VERSION_DTLS12, HITLS_VERSION_DTLS12), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 256}, #endif #ifdef HITLS_TLS_PROTO_TLCP11 #ifdef HITLS_TLS_SUITE_ECDHE_SM4_CBC_SM3 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_SM4_CBC_SM3"), .stdName = CIPHER_NAME("TLS_ECDHE_SM4_CBC_SM3"), .cipherSuite = HITLS_ECDHE_SM4_CBC_SM3, .cipherAlg = HITLS_CIPHER_SM4_CBC, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_SM2, .macAlg = HITLS_MAC_SM3, .hashAlg = HITLS_HASH_SM3, .signScheme = CERT_SIG_SCHEME_SM2_SM3, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLCP_DTLCP11, HITLS_VERSION_TLCP_DTLCP11, 0, 0), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECC_SM4_CBC_SM3 {.enable = true, .name = CIPHER_NAME("HITLS_ECC_SM4_CBC_SM3"), .stdName = CIPHER_NAME("TLS_ECC_SM4_CBC_SM3"), .cipherSuite = HITLS_ECC_SM4_CBC_SM3, .cipherAlg = HITLS_CIPHER_SM4_CBC, .kxAlg = HITLS_KEY_EXCH_ECC, .authAlg = HITLS_AUTH_SM2, .macAlg = HITLS_MAC_SM3, .hashAlg = HITLS_HASH_SM3, .signScheme = CERT_SIG_SCHEME_SM2_SM3, KEY_BLOCK_PARTITON_LENGTH(16u, 16u, 32u, 16u, 16u, 32u), VERSION_SCOPE(HITLS_VERSION_TLCP_DTLCP11, HITLS_VERSION_TLCP_DTLCP11, 0, 0), .cipherType = HITLS_CBC_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECDHE_SM4_GCM_SM3 {.enable = true, .name = CIPHER_NAME("HITLS_ECDHE_SM4_GCM_SM3"), .stdName = CIPHER_NAME("TLS_ECDHE_SM4_GCM_SM3"), .cipherSuite = HITLS_ECDHE_SM4_GCM_SM3, .cipherAlg = HITLS_CIPHER_SM4_GCM, .kxAlg = HITLS_KEY_EXCH_ECDHE, .authAlg = HITLS_AUTH_SM2, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SM3, .signScheme = CERT_SIG_SCHEME_SM2_SM3, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLCP_DTLCP11, HITLS_VERSION_TLCP_DTLCP11, 0, 0), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #ifdef HITLS_TLS_SUITE_ECC_SM4_GCM_SM3 {.enable = true, .name = CIPHER_NAME("HITLS_ECC_SM4_GCM_SM3"), .stdName = CIPHER_NAME("TLS_ECC_SM4_GCM_SM3"), .cipherSuite = HITLS_ECC_SM4_GCM_SM3, .cipherAlg = HITLS_CIPHER_SM4_GCM, .kxAlg = HITLS_KEY_EXCH_ECC, .authAlg = HITLS_AUTH_SM2, .macAlg = HITLS_MAC_AEAD, .hashAlg = HITLS_HASH_SM3, .signScheme = CERT_SIG_SCHEME_SM2_SM3, KEY_BLOCK_PARTITON_LENGTH(4u, 16u, 0u, 0u, 8u, 16u), VERSION_SCOPE(HITLS_VERSION_TLCP_DTLCP11, HITLS_VERSION_TLCP_DTLCP11, 0, 0), .cipherType = HITLS_AEAD_CIPHER, .strengthBits = 128}, #endif #endif }; const CipherSuiteCertType g_cipherSuiteAndCertTypes[] = { { HITLS_RSA_WITH_AES_128_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_256_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_128_CBC_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_256_CBC_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_128_GCM_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_256_GCM_SHA384, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_128_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_256_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_128_CCM, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_AES_256_CCM, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_128_CCM, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_128_CCM_8, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_256_CCM, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_WITH_AES_256_CCM_8, CERT_TYPE_RSA_SIGN }, { HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_PSK_WITH_AES_128_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_PSK_WITH_AES_256_CBC_SHA, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384, CERT_TYPE_RSA_SIGN }, { HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256, CERT_TYPE_RSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_128_CCM, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_ECDSA_WITH_AES_256_CCM, CERT_TYPE_ECDSA_SIGN }, { HITLS_DHE_DSS_WITH_AES_128_CBC_SHA, CERT_TYPE_DSS_SIGN }, { HITLS_DHE_DSS_WITH_AES_256_CBC_SHA, CERT_TYPE_DSS_SIGN }, { HITLS_DHE_DSS_WITH_AES_128_CBC_SHA256, CERT_TYPE_DSS_SIGN }, { HITLS_DHE_DSS_WITH_AES_256_CBC_SHA256, CERT_TYPE_DSS_SIGN }, { HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, CERT_TYPE_DSS_SIGN }, { HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, CERT_TYPE_DSS_SIGN }, { HITLS_ECDHE_SM4_CBC_SM3, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECC_SM4_CBC_SM3, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECDHE_SM4_GCM_SM3, CERT_TYPE_ECDSA_SIGN }, { HITLS_ECC_SM4_GCM_SM3, CERT_TYPE_ECDSA_SIGN }, }; /** * @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 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) { if (cipherInfo == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15858, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CFG:cipherInfo is NULL.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_INTERNAL_EXCEPTION); return HITLS_INTERNAL_EXCEPTION; } /* Obtain the cipher suite information. If the cipher suite information is successfully obtained, a response is * returned. */ for (uint32_t i = 0; i < (sizeof(g_cipherSuiteList) / sizeof(g_cipherSuiteList[0])); i++) { if (g_cipherSuiteList[i].cipherSuite == cipherSuite) { if (g_cipherSuiteList[i].enable == false) { break; } int32_t ret = memcpy_s(cipherInfo, sizeof(CipherSuiteInfo), &g_cipherSuiteList[i], sizeof(CipherSuiteInfo)); if (ret != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15859, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "CFG:memcpy failed.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } return HITLS_SUCCESS; } } BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15860, BSL_LOG_LEVEL_DEBUG, BSL_LOG_BINLOG_TYPE_RUN, "CFG: [0x%x]cipher suite is not supported.", cipherSuite, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE); return HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE; } /** * @brief Check whether the input cipher suite is supported. * * @param cipherSuite [IN] Cipher suite to be checked * * @retval true support * @retval false Not supported */ bool CFG_CheckCipherSuiteSupported(uint16_t cipherSuite) { /** @alias Check the suite and return true if supported. */ for (uint32_t i = 0; i < (sizeof(g_cipherSuiteList) / sizeof(g_cipherSuiteList[0])); i++) { if (cipherSuite == g_cipherSuiteList[i].cipherSuite) { return g_cipherSuiteList[i].enable; } } return false; } /** Check whether the version is within the allowed range */ static bool CheckTlsVersionInRange(uint16_t cipherMinVersion, uint16_t cipherMaxVersion, uint16_t cfgMinVersion, uint16_t cfgMaxVersion) { if ((cipherMaxVersion < cfgMinVersion) || (cipherMinVersion > cfgMaxVersion)) { return false; } return true; } /** Check whether the version of the TLCP is within the allowed range */ static bool CheckTLCPVersionInRange(uint16_t version, uint16_t minVersion, uint16_t maxVersion) { return (version >= minVersion) && (version <= maxVersion); } /** Check whether the version is within the allowed range. (DTLS version numbers are sorted in reverse order. For * example, DTLS 1.2 is greater than DTLS 1.3 */ static bool CheckDtlsVersionInRange(uint16_t cipherMinVersion, uint16_t cipherMaxVersion, uint16_t cfgMinVersion, uint16_t cfgMaxVersion) { if ((cipherMaxVersion > cfgMinVersion) || (cipherMinVersion < cfgMaxVersion)) { return false; } return true; } /** * @brief Check whether the input cipher suite complies with the version * * @param cipherSuite [IN] Cipher suite to be checked * minVersion [IN] Indicates the earliest version of the cipher suite * maxVersion [IN] Indicates the latest version of the cipher suite * * @retval true support * @retval false Not supported */ bool CFG_CheckCipherSuiteVersion(uint16_t cipherSuite, uint16_t minVersion, uint16_t maxVersion) { const CipherSuiteInfo *suiteInfo = NULL; /** @alias Check the suite and return true if supported. */ for (uint32_t i = 0; i < (sizeof(g_cipherSuiteList) / sizeof(g_cipherSuiteList[0])); i++) { suiteInfo = &g_cipherSuiteList[i]; if (cipherSuite == suiteInfo->cipherSuite) { /** tlcp max version equal min version */ return CheckTlsVersionInRange(suiteInfo->minVersion, suiteInfo->maxVersion, minVersion, maxVersion) || CheckDtlsVersionInRange(suiteInfo->minDtlsVersion, suiteInfo->maxDtlsVersion, minVersion, maxVersion) || CheckTLCPVersionInRange(minVersion, suiteInfo->minVersion, suiteInfo->maxVersion) || CheckTLCPVersionInRange(maxVersion, suiteInfo->minVersion, suiteInfo->maxVersion); } } return false; } /** * @brief Obtain the signature algorithm and hash algorithm by combining the parameters of the signature hash * algorithm. * * @param ctx [IN] HITLS 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) { if (ctx == NULL || signAlg == NULL || hashAlg == NULL) { return false; } const TLS_SigSchemeInfo *info = ConfigGetSignatureSchemeInfo(&ctx->config.tlsConfig, scheme); if (info == NULL) { return false; } *signAlg = info->signAlgId; *hashAlg = info->hashAlgId; return true; } /** * @brief get the group name of the signature algorithm * @param ctx [IN] HITLS context * @param scheme [IN] signature algorithm * * @retval group name */ HITLS_NamedGroup CFG_GetEcdsaCurveNameBySchemes(const HITLS_Ctx *ctx, HITLS_SignHashAlgo scheme) { const TLS_SigSchemeInfo *info = ConfigGetSignatureSchemeInfo(&ctx->config.tlsConfig, scheme); if (info == NULL) { return HITLS_NAMED_GROUP_BUTT; } uint32_t groupInfoNum = 0; const TLS_GroupInfo *groupInfo = ConfigGetGroupInfoList(&ctx->config.tlsConfig, &groupInfoNum); if (groupInfo == NULL || groupInfoNum == 0) { return HITLS_NAMED_GROUP_BUTT; } for (uint32_t i = 0; i < groupInfoNum; i++) { if (groupInfo[i].paraId == info->paraId) { return groupInfo[i].groupId; } } return HITLS_NAMED_GROUP_BUTT; } /** * @brief Obtain the certificate type based on the cipher suite * * @param cipherSuite [IN] Cipher suite * * @return Certificate type corresponding to the cipher suite */ uint8_t CFG_GetCertTypeByCipherSuite(uint16_t cipherSuite) { for (uint32_t i = 0; i < (sizeof(g_cipherSuiteAndCertTypes) / sizeof(g_cipherSuiteAndCertTypes[0])); i++) { if (cipherSuite == g_cipherSuiteAndCertTypes[i].cipherSuite) { return g_cipherSuiteAndCertTypes[i].certType; } } return CERT_TYPE_UNKNOWN; } #ifdef HITLS_TLS_CONFIG_CIPHER_SUITE /* Convert the supported version number to the corresponding character string */ static const uint8_t* ProtocolToString(uint16_t version) { const char *ret = NULL; switch (version) { case HITLS_VERSION_TLS12: ret = "TLSv1.2"; break; case HITLS_VERSION_TLS13: ret = "TLSv1.3"; break; case HITLS_VERSION_DTLS10: ret = "DTLSv1"; break; case HITLS_VERSION_DTLS12: ret = "DTLSv1.2"; break; case HITLS_VERSION_TLCP_DTLCP11: ret = "(D)TLCP1.1"; break; default: ret = "unknown"; break; } return (const uint8_t *)ret; } /* Convert the server authorization algorithm type to the corresponding character string */ static const uint8_t* AuthAlgToString(HITLS_AuthAlgo authAlg) { const char *ret = NULL; switch (authAlg) { case HITLS_AUTH_RSA: ret = "RSA"; break; case HITLS_AUTH_ECDSA: ret = "ECDSA"; break; case HITLS_AUTH_DSS: ret = "DSS"; break; case HITLS_AUTH_SM2: ret = "SM2"; break; default: ret = "unknown"; break; } return (const uint8_t *)ret; } /* Convert the key exchange algorithm type to the corresponding character string */ static const uint8_t* KeyExchAlgToString(HITLS_KeyExchAlgo kxAlg) { const char *ret = NULL; switch (kxAlg) { case HITLS_KEY_EXCH_ECDHE: ret = "ECDHE"; break; case HITLS_KEY_EXCH_DHE: ret = "DHE"; break; case HITLS_KEY_EXCH_ECDH: ret = "ECDH"; break; case HITLS_KEY_EXCH_DH: ret = "DH"; break; case HITLS_KEY_EXCH_RSA: ret = "RSA"; break; case HITLS_KEY_EXCH_PSK: ret = "PSK"; break; case HITLS_KEY_EXCH_ECC: ret = "ECC"; break; default: ret = "unknown"; break; } return (const uint8_t *)ret; } /* Convert the MAC algorithm type to the corresponding character string */ static const uint8_t* MacAlgToString(HITLS_MacAlgo macAlg) { const char *ret = NULL; switch (macAlg) { case HITLS_MAC_1: ret = "SHA1"; break; case HITLS_MAC_256: ret = "SHA256"; break; case HITLS_MAC_384: ret = "SHA384"; break; case HITLS_MAC_512: ret = "SHA512"; break; case HITLS_MAC_AEAD: ret = "AEAD"; break; case HITLS_MAC_SM3: ret = "SM3"; break; default: ret = "unknown"; break; } return (const uint8_t *)ret; } /* Convert the hash algorithm type to the corresponding character string */ static const uint8_t* HashAlgToString(HITLS_HashAlgo hashAlg) { const char *ret = NULL; switch (hashAlg) { case HITLS_HASH_MD5: ret = "MD5"; break; case HITLS_HASH_SHA1: ret = "SHA1"; break; case HITLS_HASH_SHA_256: ret = "SHA256"; break; case HITLS_HASH_SHA_384: ret = "SHA384"; break; case HITLS_HASH_SHA_512: ret = "SHA512"; break; case HITLS_HASH_SM3: ret = "SM3"; break; default: ret = "unknown"; break; } return (const uint8_t *)ret; } /* Search the corresponding index in the table based on the cipher suite. If the cipher suite is invalid, * CIPHER_SUITE_NOT_EXIST is returned */ static int32_t FindCipherSuiteIndexByCipherSuite(const uint16_t cipherSuite) { uint32_t i; for (i = 0; i < sizeof(g_cipherSuiteList) / sizeof(CipherSuiteInfo); i++) { if (g_cipherSuiteList[i].cipherSuite == cipherSuite) { return (int32_t)i; } } BSL_ERR_PUSH_ERROR(HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE); return HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE; } static int32_t GetCipherSuiteDescription(const CipherSuiteInfo *cipherSuiteInfo, uint8_t *buf, int len) { if (cipherSuiteInfo == NULL || buf == NULL || len < CIPHERSUITE_DESCRIPTION_MAXLEN) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } const uint8_t *ver, *kx, *au, *hash, *mac; static const char *format = "%-30s %-7s Kx=%-8s Au=%-5s Hash=%-22s Mac=%-4s\n"; ver = ProtocolToString(cipherSuiteInfo->minVersion); kx = KeyExchAlgToString(cipherSuiteInfo->kxAlg); au = AuthAlgToString(cipherSuiteInfo->authAlg); mac = MacAlgToString(cipherSuiteInfo->macAlg); hash = HashAlgToString(cipherSuiteInfo->hashAlg); int32_t ret = snprintf_s((char *)buf, CIPHERSUITE_DESCRIPTION_MAXLEN, CIPHERSUITE_DESCRIPTION_MAXLEN, format, cipherSuiteInfo->name, ver, kx, au, hash, mac); if (ret < 0 || ret > CIPHERSUITE_DESCRIPTION_MAXLEN - 1) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } return HITLS_SUCCESS; } /** * @brief Obtain the Symmetric-key algorithm type based on the cipher suite * * @param cipher[IN] Cipher suite * @param cipherAlg [OUT] Obtained Symmetric-key algorithm type. * @retval HITLS_SUCCESS succeeded * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetCipherId(const HITLS_Cipher *cipher, HITLS_CipherAlgo *cipherAlg) { if (cipher == NULL || cipherAlg == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *cipherAlg = cipher->cipherAlg; return HITLS_SUCCESS; } /** * @brief Obtain the hash algorithm type based on the cipher suite. * * @param cipher [IN] Cipher suite * @param hashAlg [OUT] Obtained hash algorithm type * @retval HITLS_SUCCESS succeeded * @retval For other error codes, see hitls_error.h */ int32_t HITLS_CFG_GetHashId(const HITLS_Cipher *cipher, HITLS_HashAlgo *hashAlg) { if (cipher == NULL || hashAlg == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *hashAlg = cipher->hashAlg; return HITLS_SUCCESS; } /** * @brief Obtain the MAC algorithm type based on the cipher suite. * * @param cipher [IN] Cipher suite * @param macAlg [OUT] Obtained MAC algorithm type. * @retval HITLS_SUCCESS succeeded * @retval For other error codes, see hitls_error.h */ int32_t HITLS_CFG_GetMacId(const HITLS_Cipher *cipher, HITLS_MacAlgo *macAlg) { if (cipher == NULL || macAlg == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *macAlg = cipher->macAlg; return HITLS_SUCCESS; } /** * @brief Obtain the server authorization algorithm type based on the cipher suite * * @param cipher [IN] Cipher suite * @param authAlg [OUT] Obtained server authorization type. * @retval HITLS_SUCCESS succeeded * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetAuthId(const HITLS_Cipher *cipher, HITLS_AuthAlgo *authAlg) { if (cipher == NULL || authAlg == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *authAlg = cipher->authAlg; return HITLS_SUCCESS; } /** * @brief Obtain the key exchange algorithm type based on the cipher suite. * * @param cipher [IN] Cipher suite * @param kxAlg [OUT] Obtained key exchange algorithm type. * @retval HITLS_SUCCESS succeeded * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetKeyExchId(const HITLS_Cipher *cipher, HITLS_KeyExchAlgo *kxAlg) { if (cipher == NULL || kxAlg == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *kxAlg = cipher->kxAlg; return HITLS_SUCCESS; } /** * @brief Obtain the cipher suite name based on the cipher suite. * * @param cipher [IN] Cipher suite * @retval "(NONE)" Invalid cipher suite. * @retval Name of the given cipher suite */ const uint8_t* HITLS_CFG_GetCipherSuiteName(const HITLS_Cipher *cipher) { if (cipher == NULL) { return (const uint8_t *)"(NONE)"; } return (const uint8_t *)cipher->name; } /** * @brief Obtain the RFC standard name of the cipher suite based on the cipher suite. * * @param cipher [IN] Cipher suite * * @retval "(NONE)" Invalid cipher suite. * @retval RFC standard name for the given cipher suite */ const uint8_t* HITLS_CFG_GetCipherSuiteStdName(const HITLS_Cipher *cipher) { if (cipher == NULL) { return (const uint8_t *)"(NONE)"; } return (const uint8_t *)cipher->stdName; } static int32_t FindCipherSuiteIndexByStdName(const uint8_t* stdName) { for (uint32_t i = 0; i < sizeof(g_cipherSuiteList) / sizeof(CipherSuiteInfo); i++) { if (strncmp(g_cipherSuiteList[i].stdName, (const char *)stdName, strlen(g_cipherSuiteList[i].stdName) + 1) == 0) { return (int32_t)i; } } BSL_ERR_PUSH_ERROR(HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE); return HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE; } const HITLS_Cipher* HITLS_CFG_GetCipherSuiteByStdName(const uint8_t* stdName) { if (stdName == NULL) { return NULL; } int32_t index = FindCipherSuiteIndexByStdName(stdName); if (index == HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16549, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "No proper cipher suite", 0, 0, 0, 0); return NULL; } return &g_cipherSuiteList[index]; } /** * @brief Obtain the earliest TLS version supported by the cipher suite based on the cipher suite. * * @param cipher [IN] Cipher suite * @param version [OUT] Obtain the earliest TLS version supported by the cipher suite. * @retval HITLS_SUCCESS succeeded * @retval For other error codes, see hitls_error.h. */ int32_t HITLS_CFG_GetCipherVersion(const HITLS_Cipher *cipher, int32_t *version) { if (cipher == NULL || version == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *version = cipher->minVersion; return HITLS_SUCCESS; } /** * @brief Output the description of the cipher suite as a character string. * * @param cipherSuite [IN] Cipher suite * @param buf [OUT] Output the description. * @param len [IN] Description length * @retval NULL Failed to obtain the description. * @retval Description of the cipher suite */ int32_t HITLS_CFG_GetDescription(const HITLS_Cipher *cipher, uint8_t *buf, int32_t len) { return GetCipherSuiteDescription(cipher, buf, len); } /** * @brief Determine whether to use the AEAD algorithm based on the cipher suite information. * * @param cipher [IN] Cipher suite information * @param isAead [OUT] Indicates whether to use the AEAD algorithm. * @return HITLS_SUCCESS Obtained successfully. * HITLS_NULL_INPUT The input parameter pointer is NULL. */ int32_t HITLS_CIPHER_IsAead(const HITLS_Cipher *cipher, uint8_t *isAead) { if (cipher == NULL || isAead == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *isAead = (cipher->cipherType == HITLS_AEAD_CIPHER); return HITLS_SUCCESS; } const HITLS_Cipher *HITLS_CFG_GetCipherByID(uint16_t cipherSuite) { int32_t index = FindCipherSuiteIndexByCipherSuite(cipherSuite); if (index == HITLS_CONFIG_UNSUPPORT_CIPHER_SUITE) { return NULL; } return &g_cipherSuiteList[index]; } int32_t HITLS_CFG_GetCipherSuite(const HITLS_Cipher *cipher, uint16_t *cipherSuite) { if (cipher == NULL || cipherSuite == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *cipherSuite = cipher->cipherSuite; return HITLS_SUCCESS; } #endif /* HITLS_TLS_CONFIG_CIPHER_SUITE */
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/cipher_suite.c
C
unknown
92,874
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdint.h> #include <stdbool.h> #include "hitls_build.h" #include "securec.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "bsl_log.h" #include "bsl_sal.h" #include "bsl_list.h" #include "hitls_type.h" #include "hitls_error.h" #ifdef HITLS_TLS_FEATURE_PSK #include "hitls_psk.h" #endif #ifdef HITLS_TLS_FEATURE_ALPN #include "hitls_alpn.h" #endif #include "hitls_cert_type.h" #ifdef HITLS_TLS_FEATURE_SNI #include "hitls_sni.h" #endif #include "tls.h" #include "tls_binlog_id.h" #include "cert.h" #include "crypt.h" #ifdef HITLS_TLS_FEATURE_SESSION #include "session_mgr.h" #endif #include "config_check.h" #include "config_default.h" #include "bsl_list.h" #include "rec.h" #include "hitls_cookie.h" #include "cert_method.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION #include "custom_extensions.h" #endif #ifdef HITLS_TLS_CONFIG_CIPHER_SUITE /* Define the upper limit of the group type */ #define MAX_GROUP_TYPE_NUM 128u #endif #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT #define MAX_PLAINTEXT_LEN 16384u #define MIN_MAX_SEND_FRAGMENT 512u #endif #ifdef HITLS_TLS_FEATURE_REC_INBUFFER_SIZE #define MAX_INBUFFER_SIZE 18432u #define MIN_INBUFFER_SIZE 512u #endif void CFG_CleanConfig(HITLS_Config *config) { BSL_SAL_FREE(config->cipherSuites); #ifdef HITLS_TLS_PROTO_TLS13 BSL_SAL_FREE(config->tls13CipherSuites); #endif BSL_SAL_FREE(config->pointFormats); BSL_SAL_FREE(config->groups); BSL_SAL_FREE(config->signAlgorithms); #ifdef HITLS_TLS_FEATURE_PROVIDER for (uint32_t i = 0; i < config->groupInfolen; i++) { BSL_SAL_FREE(config->groupInfo[i].name); } BSL_SAL_FREE(config->groupInfo); config->groupInfoSize = 0; config->groupInfolen = 0; for (uint32_t i = 0; i < config->sigSchemeInfolen; i++) { BSL_SAL_FREE(config->sigSchemeInfo[i].name); } BSL_SAL_FREE(config->sigSchemeInfo); config->sigSchemeInfoSize = 0; config->sigSchemeInfolen = 0; #endif #if defined(HITLS_TLS_PROTO_TLS12) && defined(HITLS_TLS_FEATURE_PSK) BSL_SAL_FREE(config->pskIdentityHint); #endif #ifdef HITLS_TLS_FEATURE_ALPN BSL_SAL_FREE(config->alpnList); #endif #ifdef HITLS_TLS_FEATURE_SNI BSL_SAL_FREE(config->serverName); #endif #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES HITLS_CFG_ClearCAList(config); #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ #ifdef HITLS_TLS_CONFIG_MANUAL_DH SAL_CRYPT_FreeDhKey(config->dhTmp); config->dhTmp = NULL; #endif #ifdef HITLS_TLS_FEATURE_SESSION SESSMGR_Free(config->sessMgr); config->sessMgr = NULL; #endif SAL_CERT_MgrCtxFree(config->certMgrCtx); config->certMgrCtx = NULL; #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION FreeCustomExtensions(config->customExts); config->customExts = NULL; #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ BSL_SAL_ReferencesFree(&(config->references)); } static void ShallowCopy(HITLS_Ctx *ctx, const HITLS_Config *srcConfig) { HITLS_Config *destConfig = &ctx->config.tlsConfig; /* * Other parameters except CipherSuite, PointFormats, Group, SignAlgorithms, Psk, SessionId, CertMgr, and SessMgr * are shallowly copied, and some of them reference globalConfig. */ destConfig->libCtx = LIBCTX_FROM_CONFIG(srcConfig); destConfig->attrName = ATTRIBUTE_FROM_CONFIG(srcConfig); destConfig->minVersion = srcConfig->minVersion; destConfig->maxVersion = srcConfig->maxVersion; destConfig->isQuietShutdown = srcConfig->isQuietShutdown; destConfig->isSupportServerPreference = srcConfig->isSupportServerPreference; destConfig->maxCertList = srcConfig->maxCertList; destConfig->isSupportExtendMasterSecret = srcConfig->isSupportExtendMasterSecret; destConfig->emptyRecordsNum = srcConfig->emptyRecordsNum; destConfig->isKeepPeerCert = srcConfig->isKeepPeerCert; destConfig->version = srcConfig->version; destConfig->originVersionMask = srcConfig->originVersionMask; #ifdef HITLS_TLS_PROTO_TLS13 destConfig->isMiddleBoxCompat = srcConfig->isMiddleBoxCompat; #endif #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT destConfig->maxSendFragment = srcConfig->maxSendFragment; #endif #ifdef HITLS_TLS_FEATURE_REC_INBUFFER_SIZE destConfig->recInbufferSize = srcConfig->recInbufferSize; #endif #ifdef HITLS_TLS_FEATURE_RENEGOTIATION destConfig->isSupportRenegotiation = srcConfig->isSupportRenegotiation; destConfig->allowClientRenegotiate = srcConfig->allowClientRenegotiate; #endif #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) destConfig->allowLegacyRenegotiate = srcConfig->allowLegacyRenegotiate; #endif #ifdef HITLS_TLS_SUITE_KX_RSA destConfig->needCheckPmsVersion = srcConfig->needCheckPmsVersion; #endif #ifdef HITLS_TLS_CONFIG_KEY_USAGE destConfig->needCheckKeyUsage = srcConfig->needCheckKeyUsage; #endif destConfig->userData = srcConfig->userData; destConfig->userDataFreeCb = srcConfig->userDataFreeCb; #ifdef HITLS_TLS_FEATURE_MODE destConfig->modeSupport = srcConfig->modeSupport; #endif destConfig->readAhead = srcConfig->readAhead; destConfig->recordPaddingCb = srcConfig->recordPaddingCb; destConfig->recordPaddingArg = srcConfig->recordPaddingArg; #ifdef HITLS_TLS_CONFIG_MANUAL_DH destConfig->isSupportDhAuto = srcConfig->isSupportDhAuto; destConfig->dhTmpCb = srcConfig->dhTmpCb; #endif #if defined(HITLS_TLS_FEATURE_RENEGOTIATION) && defined(HITLS_TLS_FEATURE_SESSION) destConfig->isResumptionOnRenego = srcConfig->isResumptionOnRenego; #endif #ifdef HITLS_TLS_FEATURE_CERT_MODE destConfig->isSupportClientVerify = srcConfig->isSupportClientVerify; destConfig->isSupportNoClientCert = srcConfig->isSupportNoClientCert; destConfig->isSupportVerifyNone = srcConfig->isSupportVerifyNone; #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET destConfig->isSupportSessionTicket = srcConfig->isSupportSessionTicket; #endif #if defined(HITLS_TLS_FEATURE_RENEGOTIATION) && defined(HITLS_TLS_FEATURE_CERT_MODE) destConfig->isSupportClientOnceVerify = srcConfig->isSupportClientOnceVerify; #endif #ifdef HITLS_TLS_FEATURE_PHA destConfig->isSupportPostHandshakeAuth = srcConfig->isSupportPostHandshakeAuth; #endif #ifdef HITLS_TLS_FEATURE_PSK destConfig->pskClientCb = srcConfig->pskClientCb; destConfig->pskServerCb = srcConfig->pskServerCb; #endif #ifdef HITLS_TLS_PROTO_TLS13 destConfig->keyExchMode = srcConfig->keyExchMode; #endif #ifdef HITLS_TLS_FEATURE_INDICATOR destConfig->infoCb = srcConfig->infoCb; destConfig->msgCb = srcConfig->msgCb; destConfig->msgArg = srcConfig->msgArg; #endif #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) destConfig->dtlsTimerCb = srcConfig->dtlsTimerCb; destConfig->dtlsPostHsTimeoutVal = srcConfig->dtlsPostHsTimeoutVal; destConfig->isSupportDtlsCookieExchange = srcConfig->isSupportDtlsCookieExchange; #endif #ifdef HITLS_TLS_FEATURE_SECURITY destConfig->securityCb = srcConfig->securityCb; destConfig->securityExData = srcConfig->securityExData; destConfig->securityLevel = srcConfig->securityLevel; #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC destConfig->isEncryptThenMac = srcConfig->isEncryptThenMac; #endif #if defined(HITLS_TLS_PROTO_TLS13) && defined(HITLS_TLS_FEATURE_PSK) destConfig->pskFindSessionCb = srcConfig->pskFindSessionCb; destConfig->pskUseSessionCb = srcConfig->pskUseSessionCb; #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET destConfig->ticketNums = srcConfig->ticketNums; #endif #ifdef HITLS_TLS_FEATURE_FLIGHT destConfig->isFlightTransmitEnable = srcConfig->isFlightTransmitEnable; #endif } static int32_t DeepCopy(void** destConfig, const void* srcConfig, uint32_t logId, uint32_t len) { BSL_SAL_FREE(*destConfig); *destConfig = BSL_SAL_Dump(srcConfig, len); if (*destConfig == NULL) { BSL_LOG_BINLOG_FIXLEN(logId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } static int32_t PointFormatsCfgDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->pointFormats != NULL) { int32_t ret = DeepCopy((void **)&destConfig->pointFormats, srcConfig->pointFormats, BINLOG_ID16584, srcConfig->pointFormatsSize * sizeof(uint8_t)); if (ret != HITLS_SUCCESS) { return ret; } destConfig->pointFormatsSize = srcConfig->pointFormatsSize; } return HITLS_SUCCESS; } static int32_t GroupCfgDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->groups != NULL) { int32_t ret = DeepCopy((void **)&destConfig->groups, srcConfig->groups, BINLOG_ID16585, srcConfig->groupsSize * sizeof(uint16_t)); if (ret != HITLS_SUCCESS) { return ret; } destConfig->groupsSize = srcConfig->groupsSize; } #ifdef HITLS_TLS_FEATURE_PROVIDER if (srcConfig->groupInfo != NULL) { for (uint32_t i = 0; i < destConfig->groupInfolen; i++) { BSL_SAL_FREE(destConfig->groupInfo[i].name); } BSL_SAL_FREE(destConfig->groupInfo); destConfig->groupInfoSize = 0; destConfig->groupInfolen = 0; destConfig->groupInfo= BSL_SAL_Calloc(srcConfig->groupInfolen, sizeof(TLS_GroupInfo)); if (destConfig->groupInfo == NULL) { return HITLS_MEMALLOC_FAIL; } for (uint32_t i = 0; i < srcConfig->groupInfolen; i++) { destConfig->groupInfo[i] = srcConfig->groupInfo[i]; destConfig->groupInfo[i].name = BSL_SAL_Dump(srcConfig->groupInfo[i].name, strlen(srcConfig->groupInfo[i].name) + 1); if (destConfig->groupInfo[i].name == NULL) { return HITLS_MEMALLOC_FAIL; } } destConfig->groupInfoSize = srcConfig->groupInfolen; destConfig->groupInfolen = srcConfig->groupInfolen; } #endif return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_TLS12) && defined(HITLS_TLS_FEATURE_PSK) static int32_t PskCfgDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->pskIdentityHint != NULL) { BSL_SAL_FREE(destConfig->pskIdentityHint); destConfig->pskIdentityHint = BSL_SAL_Dump(srcConfig->pskIdentityHint, srcConfig->hintSize * sizeof(uint8_t)); if (destConfig->pskIdentityHint == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16586, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } destConfig->hintSize = srcConfig->hintSize; } return HITLS_SUCCESS; } #endif static int32_t SignAlgorithmsCfgDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->signAlgorithms != NULL) { int32_t ret = DeepCopy((void **)&destConfig->signAlgorithms, srcConfig->signAlgorithms, BINLOG_ID16587, srcConfig->signAlgorithmsSize * sizeof(uint16_t)); if (ret != HITLS_SUCCESS) { return ret; } destConfig->signAlgorithmsSize = srcConfig->signAlgorithmsSize; } #ifdef HITLS_TLS_FEATURE_PROVIDER if (srcConfig->sigSchemeInfo != NULL) { for (uint32_t i = 0; i < destConfig->sigSchemeInfolen; i++) { BSL_SAL_FREE(destConfig->sigSchemeInfo[i].name); } BSL_SAL_FREE(destConfig->sigSchemeInfo); destConfig->sigSchemeInfoSize = 0; destConfig->sigSchemeInfolen = 0; destConfig->sigSchemeInfo = BSL_SAL_Calloc(srcConfig->sigSchemeInfolen, sizeof(TLS_SigSchemeInfo)); if (destConfig->sigSchemeInfo == NULL) { return HITLS_MEMALLOC_FAIL; } for (uint32_t i = 0; i < srcConfig->sigSchemeInfolen; i++) { destConfig->sigSchemeInfo[i] = srcConfig->sigSchemeInfo[i]; destConfig->sigSchemeInfo[i].name = BSL_SAL_Dump(srcConfig->sigSchemeInfo[i].name, strlen(srcConfig->sigSchemeInfo[i].name) + 1); if (destConfig->sigSchemeInfo[i].name == NULL) { return HITLS_MEMALLOC_FAIL; } } destConfig->sigSchemeInfoSize = srcConfig->sigSchemeInfolen; destConfig->sigSchemeInfolen = srcConfig->sigSchemeInfolen; } #endif return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_ALPN static int32_t AlpnListDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->alpnListSize == 0 || srcConfig->alpnList == NULL) { return HITLS_SUCCESS; } BSL_SAL_FREE(destConfig->alpnList); destConfig->alpnList = BSL_SAL_Dump(srcConfig->alpnList, (srcConfig->alpnListSize + 1) * sizeof(uint8_t)); if (destConfig->alpnList == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16588, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } destConfig->alpnListSize = srcConfig->alpnListSize; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_SNI static int32_t ServerNameDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->serverNameSize != 0 && srcConfig->serverName != NULL) { int32_t ret = DeepCopy((void **)&destConfig->serverName, srcConfig->serverName, BINLOG_ID16589, srcConfig->serverNameSize * sizeof(uint8_t)); if (ret != HITLS_SUCCESS) { return ret; } destConfig->serverNameSize = srcConfig->serverNameSize; } return HITLS_SUCCESS; } #endif static int32_t CipherSuiteDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->cipherSuites != NULL) { int32_t ret = DeepCopy((void **)&destConfig->cipherSuites, srcConfig->cipherSuites, BINLOG_ID16590, srcConfig->cipherSuitesSize * sizeof(uint16_t)); if (ret != HITLS_SUCCESS) { return ret; } destConfig->cipherSuitesSize = srcConfig->cipherSuitesSize; } #ifdef HITLS_TLS_PROTO_TLS13 if (srcConfig->tls13CipherSuites != NULL) { int32_t ret = DeepCopy((void **)&destConfig->tls13CipherSuites, srcConfig->tls13CipherSuites, BINLOG_ID16591, srcConfig->tls13cipherSuitesSize * sizeof(uint16_t)); if (ret != HITLS_SUCCESS) { BSL_SAL_FREE(destConfig->cipherSuites); return ret; } destConfig->tls13cipherSuitesSize = srcConfig->tls13cipherSuitesSize; } #endif return HITLS_SUCCESS; } static int32_t CertMgrDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (!SAL_CERT_MgrIsEnable()) { return HITLS_SUCCESS; } destConfig->certMgrCtx = SAL_CERT_MgrCtxDup(srcConfig->certMgrCtx); if (destConfig->certMgrCtx == NULL) { return HITLS_CERT_ERR_MGR_DUP; } return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SESSION_ID static int32_t SessionIdCtxCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->sessionIdCtxSize != 0 && memcpy_s(destConfig->sessionIdCtx, sizeof(destConfig->sessionIdCtx), srcConfig->sessionIdCtx, srcConfig->sessionIdCtxSize) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16592, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); return HITLS_MEMCPY_FAIL; } destConfig->sessionIdCtxSize = srcConfig->sessionIdCtxSize; return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_SESSION_ID */ #ifdef HITLS_TLS_FEATURE_SESSION static int32_t SessMgrDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { destConfig->sessMgr = SESSMGR_Dup(srcConfig->sessMgr); if (destConfig->sessMgr == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16593, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "MGR_Dup fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } int32_t HITLS_CFG_SetSessionTimeout(HITLS_Config *config, uint64_t timeout) { if (config == NULL || config->sessMgr == NULL) { return HITLS_NULL_INPUT; } SESSMGR_SetTimeout(config->sessMgr, timeout); return HITLS_SUCCESS; } int32_t HITLS_CFG_GetSessionTimeout(const HITLS_Config *config, uint64_t *timeout) { if (config == NULL || config->sessMgr == NULL || timeout == NULL) { return HITLS_NULL_INPUT; } *timeout = SESSMGR_GetTimeout(config->sessMgr); return HITLS_SUCCESS; } int32_t HITLS_CFG_SetNewSessionCb(HITLS_Config *config, const HITLS_NewSessionCb newSessionCb) { if (config == NULL) { return HITLS_NULL_INPUT; } config->newSessionCb = newSessionCb; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH static int32_t CryptKeyDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->dhTmp != NULL) { destConfig->dhTmp = SAL_CRYPT_DupDhKey(srcConfig->dhTmp); if (destConfig->dhTmp == NULL) { return HITLS_CONFIG_DUP_DH_KEY_FAIL; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES void FreeNode(HITLS_TrustedCANode *node) { BSL_SAL_FREE(node->data); BSL_SAL_FREE(node); return; } static HITLS_TrustedCANode *DupNameNode(const HITLS_TrustedCANode *src) { /* Src is not null. */ HITLS_TrustedCANode *dest = BSL_SAL_Malloc(sizeof(HITLS_TrustedCANode)); if (dest == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return NULL; } dest->caType = src->caType; // nameValue dest->dataSize = src->dataSize; if (dest->dataSize != 0) { dest->data = BSL_SAL_Dump(src->data, src->dataSize); if (dest->data == NULL) { BSL_SAL_Free(dest); BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL); return NULL; } } return dest; } static int32_t CaListDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { if (srcConfig->caList != NULL) { destConfig->caList = BSL_LIST_Copy(srcConfig->caList, (BSL_LIST_PFUNC_DUP)DupNameNode, (BSL_LIST_PFUNC_FREE)FreeNode); if (destConfig->caList == NULL) { return HITLS_MEMCPY_FAIL; } } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION static int32_t CustomExtsDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { destConfig->customExts = DupCustomExtensions(srcConfig->customExts); if (srcConfig->customExts != NULL && destConfig->customExts == NULL) { return HITLS_MEMALLOC_FAIL; } return HITLS_SUCCESS; } #endif /* HITLS_TLS_FEATURE_CUSTOM_EXTENSION */ static int32_t BasicConfigDeepCopy(HITLS_Config *destConfig, const HITLS_Config *srcConfig) { int32_t ret = HITLS_SUCCESS; const struct { int32_t (*copyFunc)(HITLS_Config *destConfig, const HITLS_Config *srcConfig); } copyFeatures[] = { #ifdef HITLS_TLS_FEATURE_SESSION_ID {SessionIdCtxCopy}, #endif {CertMgrDeepCopy}, #ifdef HITLS_TLS_FEATURE_SESSION {SessMgrDeepCopy}, #endif #ifdef HITLS_TLS_FEATURE_ALPN {AlpnListDeepCopy}, #endif #ifdef HITLS_TLS_FEATURE_SNI {ServerNameDeepCopy}, #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH {CryptKeyDeepCopy}, #endif #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES {CaListDeepCopy}, #endif #ifdef HITLS_TLS_FEATURE_CUSTOM_EXTENSION {CustomExtsDeepCopy}, #endif }; for (size_t i = 0; i < sizeof(copyFeatures) / sizeof(copyFeatures[0]); i++) { if (copyFeatures[i].copyFunc != NULL) { ret = copyFeatures[i].copyFunc(destConfig, srcConfig); if (ret != HITLS_SUCCESS) { return ret; } } } return HITLS_SUCCESS; } int32_t DumpConfig(HITLS_Ctx *ctx, const HITLS_Config *srcConfig) { int32_t ret; HITLS_Config *destConfig = &ctx->config.tlsConfig; // shallow copy ShallowCopy(ctx, srcConfig); ret = CipherSuiteDeepCopy(destConfig, srcConfig); if (ret != HITLS_SUCCESS) { goto EXIT; } ret = PointFormatsCfgDeepCopy(destConfig, srcConfig); if (ret != HITLS_SUCCESS) { goto EXIT; } ret = GroupCfgDeepCopy(destConfig, srcConfig); if (ret != HITLS_SUCCESS) { goto EXIT; } ret = SignAlgorithmsCfgDeepCopy(destConfig, srcConfig); if (ret != HITLS_SUCCESS) { goto EXIT; } #if defined(HITLS_TLS_PROTO_TLS12) && defined(HITLS_TLS_FEATURE_PSK) ret = PskCfgDeepCopy(destConfig, srcConfig); if (ret != HITLS_SUCCESS) { goto EXIT; } #endif ret = BasicConfigDeepCopy(destConfig, srcConfig); if (ret != HITLS_SUCCESS) { goto EXIT; } return HITLS_SUCCESS; EXIT: CFG_CleanConfig(destConfig); return ret; } HITLS_Config *CreateConfig(void) { HITLS_Config *newConfig = BSL_SAL_Calloc(1u, sizeof(HITLS_Config)); if (newConfig == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16594, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return NULL; } if (BSL_SAL_ReferencesInit(&(newConfig->references)) != BSL_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16595, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "ReferencesInit fail", 0, 0, 0, 0); BSL_SAL_FREE(newConfig); return NULL; } return newConfig; } #ifdef HITLS_TLS_PROTO_DTLS12 HITLS_Config *HITLS_CFG_NewDTLS12Config(void) { return HITLS_CFG_ProviderNewDTLS12Config(NULL, NULL); } HITLS_Config *HITLS_CFG_ProviderNewDTLS12Config(HITLS_Lib_Ctx *libCtx, const char *attrName) { HITLS_Config *newConfig = CreateConfig(); if (newConfig == NULL) { return NULL; } newConfig->version |= DTLS12_VERSION_BIT; // Enable DTLS 1.2 if (DefaultConfig(libCtx, attrName, HITLS_VERSION_DTLS12, newConfig) != HITLS_SUCCESS) { BSL_SAL_FREE(newConfig); return NULL; } newConfig->originVersionMask = newConfig->version; return newConfig; } #endif #ifdef HITLS_TLS_PROTO_DTLCP11 HITLS_Config *HITLS_CFG_NewDTLCPConfig(void) { return HITLS_CFG_ProviderNewDTLCPConfig(NULL, NULL); } HITLS_Config *HITLS_CFG_ProviderNewDTLCPConfig(HITLS_Lib_Ctx *libCtx, const char *attrName) { HITLS_Config *newConfig = CreateConfig(); if (newConfig == NULL) { return NULL; } newConfig->version |= DTLCP11_VERSION_BIT; // Enable DTLCP 1.1 if (DefaultConfig(libCtx, attrName, HITLS_VERSION_TLCP_DTLCP11, newConfig) != HITLS_SUCCESS) { BSL_SAL_FREE(newConfig); return NULL; } newConfig->originVersionMask = newConfig->version; return newConfig; } #endif #ifdef HITLS_TLS_PROTO_TLCP11 HITLS_Config *HITLS_CFG_NewTLCPConfig(void) { return HITLS_CFG_ProviderNewTLCPConfig(NULL, NULL); } HITLS_Config *HITLS_CFG_ProviderNewTLCPConfig(HITLS_Lib_Ctx *libCtx, const char *attrName) { HITLS_Config *newConfig = CreateConfig(); if (newConfig == NULL) { return NULL; } newConfig->version |= TLCP11_VERSION_BIT; // Enable TLCP 1.1 if (DefaultConfig(libCtx, attrName, HITLS_VERSION_TLCP_DTLCP11, newConfig) != HITLS_SUCCESS) { BSL_SAL_FREE(newConfig); return NULL; } newConfig->originVersionMask = newConfig->version; return newConfig; } #endif #ifdef HITLS_TLS_PROTO_TLS12 HITLS_Config *HITLS_CFG_NewTLS12Config(void) { return HITLS_CFG_ProviderNewTLS12Config(NULL, NULL); } HITLS_Config *HITLS_CFG_ProviderNewTLS12Config(HITLS_Lib_Ctx *libCtx, const char *attrName) { HITLS_Config *newConfig = CreateConfig(); if (newConfig == NULL) { return NULL; } /* Initialize the version */ newConfig->version |= TLS12_VERSION_BIT; // Enable TLS 1.2 if (DefaultConfig(libCtx, attrName, HITLS_VERSION_TLS12, newConfig) != HITLS_SUCCESS) { BSL_SAL_FREE(newConfig); return NULL; } newConfig->originVersionMask = newConfig->version; return newConfig; } #endif #ifdef HITLS_TLS_PROTO_ALL HITLS_Config *HITLS_CFG_NewTLSConfig(void) { return HITLS_CFG_ProviderNewTLSConfig(NULL, NULL); } HITLS_Config *HITLS_CFG_ProviderNewTLSConfig(HITLS_Lib_Ctx *libCtx, const char *attrName) { HITLS_Config *newConfig = CreateConfig(); if (newConfig == NULL) { return NULL; } newConfig->version |= TLS_VERSION_MASK; newConfig->libCtx = libCtx; newConfig->attrName = attrName; if (DefaultTlsAllConfig(newConfig) != HITLS_SUCCESS) { BSL_SAL_FREE(newConfig); return NULL; } newConfig->originVersionMask = newConfig->version; return newConfig; } #endif #ifdef HITLS_TLS_PROTO_DTLS HITLS_Config *HITLS_CFG_NewDTLSConfig(void) { return HITLS_CFG_ProviderNewDTLSConfig(NULL, NULL); } HITLS_Config *HITLS_CFG_ProviderNewDTLSConfig(HITLS_Lib_Ctx *libCtx, const char *attrName) { HITLS_Config *newConfig = CreateConfig(); if (newConfig == NULL) { return NULL; } newConfig->version |= DTLS_VERSION_MASK; // Enable All Versions newConfig->libCtx = libCtx; newConfig->attrName = attrName; if (DefaultDtlsAllConfig(newConfig) != HITLS_SUCCESS) { BSL_SAL_FREE(newConfig); return NULL; } newConfig->originVersionMask = newConfig->version; return newConfig; } #endif void HITLS_CFG_FreeConfig(HITLS_Config *config) { if (config == NULL) { return; } int ret = 0; (void)BSL_SAL_AtomicDownReferences(&(config->references), &ret); if (ret > 0) { return; } CFG_CleanConfig(config); #ifdef HITLS_TLS_CONFIG_USER_DATA if (config->userData != NULL && config->userDataFreeCb != NULL) { (void)config->userDataFreeCb(config->userData); config->userData = NULL; } #endif BSL_SAL_FREE(config); return; } int32_t HITLS_CFG_UpRef(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } int ret = 0; (void)BSL_SAL_AtomicUpReferences(&(config->references), &ret); (void)ret; return HITLS_SUCCESS; } uint32_t MapVersion2VersionBit(bool isDatagram, uint16_t version) { (void)isDatagram; uint32_t ret = 0; switch (version) { case HITLS_VERSION_TLS12: ret = TLS12_VERSION_BIT; break; case HITLS_VERSION_TLS13: ret = TLS13_VERSION_BIT; break; case HITLS_VERSION_TLCP_DTLCP11: if (isDatagram) { ret = DTLCP11_VERSION_BIT; } else { ret = TLCP11_VERSION_BIT; } break; case HITLS_VERSION_DTLS12: ret = DTLS12_VERSION_BIT; break; default: break; } return ret; } #ifdef HITLS_TLS_PROTO_ALL static int ChangeVersionMask(HITLS_Config *config, uint16_t minVersion, uint16_t maxVersion) { uint32_t originVersionMask = config->originVersionMask; uint32_t versionMask = 0; uint32_t versionBit = 0; /* Creating a DTLS version but setting a TLS version is invalid. */ if (originVersionMask == DTLS_VERSION_MASK) { if (IS_DTLS_VERSION(minVersion) == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16596, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Config min version [0x%x] err.", minVersion, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_VERSION); return HITLS_CONFIG_INVALID_VERSION; } } if (originVersionMask == TLS_VERSION_MASK) { /* Creating a TLS version but setting a DTLS version is invalid. */ if (IS_DTLS_VERSION(minVersion)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16597, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "minVersion err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_VERSION); return HITLS_CONFIG_INVALID_VERSION; } for (uint16_t version = minVersion; version <= maxVersion; version++) { versionBit = MapVersion2VersionBit(IS_SUPPORT_DATAGRAM(originVersionMask), version); versionMask |= versionBit; } if ((versionMask & originVersionMask) == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16598, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Config version err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_VERSION); return HITLS_CONFIG_INVALID_VERSION; } config->version = versionMask; return HITLS_SUCCESS; } return HITLS_SUCCESS; } static int32_t CheckVersionValid(HITLS_Config *config, uint16_t minVersion, uint16_t maxVersion) { if ((minVersion < HITLS_VERSION_SSL30 && minVersion != 0) || (minVersion == HITLS_VERSION_SSL30 && config->minVersion != HITLS_VERSION_SSL30) || (maxVersion <= HITLS_VERSION_SSL30 && maxVersion != 0)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16599, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Config version err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_VERSION); return HITLS_CONFIG_INVALID_VERSION; } return HITLS_SUCCESS; } static void ChangeTmpVersion(HITLS_Config *config, uint16_t *tmpMinVersion, uint16_t *tmpMaxVersion) { if (*tmpMinVersion == 0) { if (config->originVersionMask == DTLS_VERSION_MASK) { *tmpMinVersion = HITLS_VERSION_DTLS12; } else { *tmpMinVersion = HITLS_VERSION_TLS12; } } else if (*tmpMaxVersion == 0) { if (config->originVersionMask == DTLS_VERSION_MASK) { *tmpMaxVersion = HITLS_VERSION_DTLS12; } else { *tmpMaxVersion = HITLS_VERSION_TLS13; } } return; } #endif int32_t HITLS_CFG_SetVersion(HITLS_Config *config, uint16_t minVersion, uint16_t maxVersion) { if (config == NULL) { return HITLS_NULL_INPUT; } int32_t ret = 0; #ifdef HITLS_TLS_PROTO_ALL if (config->minVersion == minVersion && config->maxVersion == maxVersion && minVersion != 0 && maxVersion != 0) { return HITLS_SUCCESS; } /* TLCP cannot be supported by setting the version number. They can be * initialized only by using the corresponding configuration initialization interface. */ ret = CheckVersionValid(config, minVersion, maxVersion); if (ret != HITLS_SUCCESS) { return ret; } config->minVersion = 0; config->maxVersion = 0; /* If both the latest version and the earliest version supported are 0, clear the versionMask. */ if (minVersion == maxVersion && minVersion == 0) { config->version = 0; return HITLS_SUCCESS; } #endif uint16_t tmpMinVersion = minVersion; uint16_t tmpMaxVersion = maxVersion; #ifdef HITLS_TLS_PROTO_ALL ChangeTmpVersion(config, &tmpMinVersion, &tmpMaxVersion); #endif ret = CheckVersion(tmpMinVersion, tmpMaxVersion); if (ret != HITLS_SUCCESS) { return ret; } #ifdef HITLS_TLS_PROTO_ALL /* In invalid cases, both maxVersion and minVersion are 0 */ if (ChangeVersionMask(config, tmpMinVersion, tmpMaxVersion) == HITLS_SUCCESS) { #endif config->minVersion = tmpMinVersion; config->maxVersion = tmpMaxVersion; #ifdef HITLS_TLS_PROTO_ALL } #endif return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_ALL int32_t HITLS_CFG_SetVersionForbid(HITLS_Config *config, uint32_t noVersion) { if (config == NULL) { return HITLS_NULL_INPUT; } // Now only DTLS1.2 is supported, so single version is not supported (disable to version 0) if ((config->originVersionMask & TLS_VERSION_MASK) == TLS_VERSION_MASK) { uint32_t noVersionBit = MapVersion2VersionBit(IS_SUPPORT_DATAGRAM(config->originVersionMask), (uint16_t)noVersion); if ((config->version & (~noVersionBit)) == 0) { return HITLS_SUCCESS; // Not all is disabled but the return value is SUCCESS } config->version &= ~noVersionBit; uint32_t versionBits[] = { TLS12_VERSION_BIT, TLS13_VERSION_BIT}; uint16_t versions[] = { HITLS_VERSION_TLS12, HITLS_VERSION_TLS13}; uint32_t versionBitsSize = sizeof(versionBits) / sizeof(uint32_t); for (uint32_t i = 0; i < versionBitsSize; i++) { if ((config->version & versionBits[i]) == versionBits[i]) { config->minVersion = versions[i]; break; } } for (int i = (int)versionBitsSize - 1; i >= 0; i--) { if ((config->version & versionBits[i]) == versionBits[i]) { config->maxVersion = versions[i]; break; } } } return HITLS_SUCCESS; } #endif static void GetCipherSuitesCnt(const uint16_t *cipherSuites, uint32_t cipherSuitesSize, uint32_t *tls13CipherSize, uint32_t *tlsCipherSize) { (void)cipherSuites; uint32_t tmpCipherSize = *tlsCipherSize; uint32_t tmpTls13CipherSize = *tls13CipherSize; for (uint32_t i = 0; i < cipherSuitesSize; i++) { #ifdef HITLS_TLS_PROTO_TLS13 if (cipherSuites[i] >= HITLS_AES_128_GCM_SHA256 && cipherSuites[i] <= HITLS_AES_128_CCM_8_SHA256) { tmpTls13CipherSize++; continue; } #endif tmpCipherSize++; } *tls13CipherSize = tmpTls13CipherSize; *tlsCipherSize = tmpCipherSize; } int32_t HITLS_CFG_SetCipherSuites(HITLS_Config *config, const uint16_t *cipherSuites, uint32_t cipherSuitesSize) { if (config == NULL || cipherSuites == NULL || cipherSuitesSize == 0) { return HITLS_NULL_INPUT; } if (cipherSuitesSize > HITLS_CFG_MAX_SIZE) { return HITLS_CONFIG_INVALID_LENGTH; } uint32_t tlsCipherSize = 0; uint32_t validTlsCipher = 0; uint32_t tls13CipherSize = 0; #ifdef HITLS_TLS_PROTO_TLS13 uint32_t validTls13Cipher = 0; #endif GetCipherSuitesCnt(cipherSuites, cipherSuitesSize, &tls13CipherSize, &tlsCipherSize); uint16_t *cipherSuite = BSL_SAL_Calloc(1u, (tlsCipherSize + 1) * sizeof(uint16_t)); if (cipherSuite == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16600, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } #ifdef HITLS_TLS_PROTO_TLS13 uint16_t *tls13CipherSuite = BSL_SAL_Calloc(1u, (tls13CipherSize + 1) * sizeof(uint16_t)); if (tls13CipherSuite == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16601, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); BSL_SAL_FREE(cipherSuite); return HITLS_MEMALLOC_FAIL; } #endif for (uint32_t i = 0; i < cipherSuitesSize; i++) { if (CFG_CheckCipherSuiteSupported(cipherSuites[i]) != true) { continue; } if (cipherSuites[i] >= HITLS_AES_128_GCM_SHA256 && cipherSuites[i] <= HITLS_AES_128_CCM_8_SHA256) { #ifdef HITLS_TLS_PROTO_TLS13 tls13CipherSuite[validTls13Cipher] = cipherSuites[i]; validTls13Cipher++; #endif continue; } cipherSuite[validTlsCipher] = cipherSuites[i]; validTlsCipher++; } #ifdef HITLS_TLS_PROTO_TLS13 if (validTls13Cipher == 0) { BSL_SAL_FREE(tls13CipherSuite); } else { BSL_SAL_FREE(config->tls13CipherSuites); config->tls13CipherSuites = tls13CipherSuite; config->tls13cipherSuitesSize = validTls13Cipher; } #endif if (validTlsCipher == 0) { BSL_SAL_FREE(cipherSuite); } else { BSL_SAL_FREE(config->cipherSuites); config->cipherSuites = cipherSuite; config->cipherSuitesSize = validTlsCipher; } if (validTlsCipher == 0 #ifdef HITLS_TLS_PROTO_TLS13 && validTls13Cipher == 0 #endif ) { return HITLS_CONFIG_NO_SUITABLE_CIPHER_SUITE; } return HITLS_SUCCESS; } int32_t HITLS_CFG_SetEcPointFormats(HITLS_Config *config, const uint8_t *pointFormats, uint32_t pointFormatsSize) { if ((config == NULL) || (pointFormats == NULL) || (pointFormatsSize == 0)) { return HITLS_NULL_INPUT; } if (pointFormatsSize > HITLS_CFG_MAX_SIZE) { return HITLS_CONFIG_INVALID_LENGTH; } uint8_t *newData = BSL_SAL_Dump(pointFormats, pointFormatsSize * sizeof(uint8_t)); if (newData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16602, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } BSL_SAL_FREE(config->pointFormats); config->pointFormats = newData; config->pointFormatsSize = pointFormatsSize; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetGroups(HITLS_Config *config, const uint16_t *groups, uint32_t groupsSize) { if ((config == NULL) || (groups == NULL) || (groupsSize == 0u)) { return HITLS_NULL_INPUT; } if (groupsSize > HITLS_CFG_MAX_SIZE) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } uint16_t *newData = BSL_SAL_Dump(groups, groupsSize * sizeof(uint16_t)); if (newData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16603, 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; } BSL_SAL_FREE(config->groups); config->groups = newData; config->groupsSize = groupsSize; return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HITLS_CFG_SetCookieGenCb(HITLS_Config *config, HITLS_AppGenCookieCb callback) { if (config == NULL || callback == NULL) { return HITLS_NULL_INPUT; } config->appGenCookieCb = callback; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetCookieVerifyCb(HITLS_Config *config, HITLS_AppVerifyCookieCb callback) { if (config == NULL || callback == NULL) { return HITLS_NULL_INPUT; } config->appVerifyCookieCb = callback; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetDtlsTimerCb(HITLS_Config *config, HITLS_DtlsTimerCb callback) { if (config == NULL || callback == NULL) { return HITLS_NULL_INPUT; } config->dtlsTimerCb = callback; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_CLIENT_HELLO_CB int32_t HITLS_CFG_SetClientHelloCb(HITLS_Config *config, HITLS_ClientHelloCb callback, void *arg) { if (config == NULL || callback == NULL) { return HITLS_NULL_INPUT; } config->clientHelloCb = callback; config->clientHelloCbArg = arg; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH int32_t HITLS_CFG_SetDhAutoSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportDhAuto = support; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetTmpDh(HITLS_Config *config, HITLS_CRYPT_Key *dhPkey) { if ((config == NULL) || (dhPkey == NULL)) { return HITLS_NULL_INPUT; } #ifdef HITLS_TLS_FEATURE_SECURITY int32_t secBits = 0; /* Temporary DH security check */ int32_t ret = SAL_CERT_KeyCtrl(config, dhPkey, CERT_KEY_CTRL_GET_SECBITS, NULL, (void *)&secBits); if (ret != HITLS_SUCCESS) { return HITLS_CERT_KEY_CTRL_ERR_GET_SECBITS; } ret = SECURITY_CfgCheck(config, HITLS_SECURITY_SECOP_TMP_DH, secBits, 0, dhPkey); if (ret != SECURITY_SUCCESS) { return HITLS_CRYPT_ERR_DH; } #endif /* HITLS_TLS_FEATURE_SECURITY */ SAL_CRYPT_FreeDhKey(config->dhTmp); config->dhTmp = dhPkey; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetDhAutoSupport(HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportDhAuto; return HITLS_SUCCESS; } #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ #ifdef HITLS_TLS_SUITE_KX_RSA int32_t HITLS_CFG_SetNeedCheckPmsVersion(HITLS_Config *config, bool needCheck) { if (config == NULL) { return HITLS_NULL_INPUT; } config->needCheckPmsVersion = needCheck; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_MODE int32_t HITLS_CFG_SetModeSupport(HITLS_Config *config, uint32_t mode) { if (config == NULL) { return HITLS_NULL_INPUT; } config->modeSupport |= mode; return HITLS_SUCCESS; } int32_t HITLS_CFG_ClearModeSupport(HITLS_Config *config, uint32_t mode) { if (config == NULL) { return HITLS_NULL_INPUT; } config->modeSupport &= (~mode); return HITLS_SUCCESS; } int32_t HITLS_CFG_GetModeSupport(const HITLS_Config *config, uint32_t *mode) { if (config == NULL || mode == NULL) { return HITLS_NULL_INPUT; } *mode = config->modeSupport; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONFIG_USER_DATA void *HITLS_CFG_GetConfigUserData(const HITLS_Config *config) { if (config == NULL) { return NULL; } return config->userData; } int32_t HITLS_CFG_SetConfigUserData(HITLS_Config *config, void *userData) { if (config == NULL) { return HITLS_NULL_INPUT; } config->userData = userData; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetConfigUserDataFreeCb(HITLS_Config *config, HITLS_ConfigUserDataFreeCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } config->userDataFreeCb = callback; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONFIG_CERT int32_t HITLS_CFG_SetMaxCertList(HITLS_Config *config, uint32_t maxSize) { if (config == NULL) { return HITLS_NULL_INPUT; } config->maxCertList = maxSize; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetMaxCertList(const HITLS_Config *config, uint32_t *maxSize) { if (config == NULL || maxSize == NULL) { return HITLS_NULL_INPUT; } *maxSize = config->maxCertList; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH int32_t HITLS_CFG_SetTmpDhCb(HITLS_Config *config, HITLS_DhTmpCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } config->dhTmpCb = callback; return HITLS_SUCCESS; } #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ #ifdef HITLS_TLS_CONFIG_RECORD_PADDING int32_t HITLS_CFG_SetRecordPaddingCb(HITLS_Config *config, HITLS_RecordPaddingCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } config->recordPaddingCb = callback; return HITLS_SUCCESS; } HITLS_RecordPaddingCb HITLS_CFG_GetRecordPaddingCb(HITLS_Config *config) { if (config == NULL) { return NULL; } return config->recordPaddingCb; } int32_t HITLS_CFG_SetRecordPaddingCbArg(HITLS_Config *config, void *arg) { if (config == NULL) { return HITLS_NULL_INPUT; } config->recordPaddingArg = arg; return HITLS_SUCCESS; } void *HITLS_CFG_GetRecordPaddingCbArg(HITLS_Config *config) { if (config == NULL) { return NULL; } return config->recordPaddingArg; } #endif #ifdef HITLS_TLS_CONFIG_KEY_USAGE int32_t HITLS_CFG_SetCheckKeyUsage(HITLS_Config *config, bool isCheck) { if (config == NULL) { return HITLS_NULL_INPUT; } config->needCheckKeyUsage = isCheck; return HITLS_SUCCESS; } #endif int32_t HITLS_CFG_SetReadAhead(HITLS_Config *config, int32_t onOff) { if (config == NULL) { return HITLS_NULL_INPUT; } config->readAhead = onOff; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetReadAhead(HITLS_Config *config, int32_t *onOff) { if (config == NULL || onOff == NULL) { return HITLS_NULL_INPUT; } *onOff = config->readAhead; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetSignature(HITLS_Config *config, const uint16_t *signAlgs, uint16_t signAlgsSize) { if ((config == NULL) || (signAlgs == NULL) || (signAlgsSize == 0)) { return HITLS_NULL_INPUT; } if (signAlgsSize > HITLS_CFG_MAX_SIZE) { return HITLS_CONFIG_INVALID_LENGTH; } uint16_t *newData = BSL_SAL_Dump(signAlgs, signAlgsSize * sizeof(uint16_t)); if (newData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16605, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } BSL_SAL_FREE(config->signAlgorithms); config->signAlgorithms = newData; config->signAlgorithmsSize = signAlgsSize; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SNI int32_t HITLS_CFG_SetServerName(HITLS_Config *config, uint8_t *serverName, uint32_t serverNameStrlen) { if ((config == NULL) || (serverName == NULL) || (serverNameStrlen == 0)) { return HITLS_NULL_INPUT; } if (serverNameStrlen > HITLS_CFG_MAX_SIZE) { return HITLS_CONFIG_INVALID_LENGTH; } uint32_t serverNameSize = serverNameStrlen; if (serverName[serverNameStrlen - 1] != '\0') { serverNameSize += 1; } uint8_t *newData = (uint8_t *) BSL_SAL_Malloc(serverNameSize * sizeof(uint8_t)); if (newData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16606, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(newData, serverNameSize, serverName, serverNameStrlen); newData[serverNameSize - 1] = '\0'; BSL_SAL_FREE(config->serverName); config->serverName = newData; config->serverNameSize = serverNameSize; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetServerName(HITLS_Config *config, uint8_t **serverName, uint32_t *serverNameStrlen) { if (config == NULL || serverName == NULL || serverNameStrlen == NULL) { return HITLS_NULL_INPUT; } *serverName = config->serverName; *serverNameStrlen = config->serverNameSize; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetServerNameCb(HITLS_Config *config, HITLS_SniDealCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } config->sniDealCb = callback; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetServerNameArg(HITLS_Config *config, void *arg) { if (config == NULL) { return HITLS_NULL_INPUT; } config->sniArg = arg; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetServerNameCb(HITLS_Config *config, HITLS_SniDealCb *callback) { if (config == NULL || callback == NULL) { return HITLS_NULL_INPUT; } *callback = config->sniDealCb; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetServerNameArg(HITLS_Config *config, void **arg) { if (config == NULL || arg == NULL) { return HITLS_NULL_INPUT; } *arg = config->sniArg; return HITLS_SUCCESS; } #endif int32_t HITLS_CFG_SetRenegotiationSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportRenegotiation = support; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_CFG_SetClientRenegotiateSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->allowClientRenegotiate = support; return HITLS_SUCCESS; } #endif #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) int32_t HITLS_CFG_SetLegacyRenegotiateSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->allowLegacyRenegotiate = support; return HITLS_SUCCESS; } #endif /* defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) */ #if defined(HITLS_TLS_FEATURE_RENEGOTIATION) && defined(HITLS_TLS_FEATURE_SESSION) int32_t HITLS_CFG_SetResumptionOnRenegoSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isResumptionOnRenego = support; return HITLS_SUCCESS; } #endif int32_t HITLS_CFG_SetExtenedMasterSecretSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportExtendMasterSecret = support; return HITLS_SUCCESS; } #if defined(HITLS_TLS_FEATURE_PSK) && (defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12)) int32_t HITLS_CFG_SetPskIdentityHint(HITLS_Config *config, const uint8_t *hint, uint32_t hintSize) { if ((config == NULL) || (hint == NULL) || (hintSize == 0)) { return HITLS_NULL_INPUT; } if (hintSize > HITLS_IDENTITY_HINT_MAX_SIZE) { return HITLS_CONFIG_INVALID_LENGTH; } uint8_t *newData = BSL_SAL_Dump(hint, hintSize * sizeof(uint8_t)); if (newData == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16607, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } BSL_SAL_FREE(config->pskIdentityHint); config->pskIdentityHint = newData; config->hintSize = hintSize; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_PSK // Configure clientCb, which is used to obtain the PSK through identity hints int32_t HITLS_CFG_SetPskClientCallback(HITLS_Config *config, HITLS_PskClientCb callback) { if (config == NULL || callback == NULL) { return HITLS_NULL_INPUT; } config->pskClientCb = callback; return HITLS_SUCCESS; } // Set serverCb to obtain the PSK through identity. int32_t HITLS_CFG_SetPskServerCallback(HITLS_Config *config, HITLS_PskServerCb callback) { if (config == NULL || callback == NULL) { return HITLS_NULL_INPUT; } config->pskServerCb = callback; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_SESSION_TICKET int32_t HITLS_CFG_SetSessionTicketSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportSessionTicket = support; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_RENEGOTIATION int32_t HITLS_CFG_GetRenegotiationSupport(const HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportRenegotiation; return HITLS_SUCCESS; } #endif int32_t HITLS_CFG_GetExtenedMasterSecretSupport(HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportExtendMasterSecret; return HITLS_SUCCESS; } #if defined(HITLS_TLS_FEATURE_SESSION_TICKET) int32_t HITLS_CFG_GetSessionTicketSupport(const HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportSessionTicket; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetTicketKeyCallback(HITLS_Config *config, HITLS_TicketKeyCb callback) { if (config == NULL || config->sessMgr == NULL) { return HITLS_NULL_INPUT; } SESSMGR_SetTicketKeyCb(config->sessMgr, callback); return HITLS_SUCCESS; } int32_t HITLS_CFG_GetSessionTicketKey(const HITLS_Config *config, uint8_t *key, uint32_t keySize, uint32_t *outSize) { if (config == NULL || config->sessMgr == NULL || key == NULL || outSize == NULL) { return HITLS_NULL_INPUT; } return SESSMGR_GetTicketKey(config->sessMgr, key, keySize, outSize); } int32_t HITLS_CFG_SetSessionTicketKey(HITLS_Config *config, const uint8_t *key, uint32_t keySize) { if (config == NULL || config->sessMgr == NULL || key == NULL || (keySize != HITLS_TICKET_KEY_NAME_SIZE + HITLS_TICKET_KEY_SIZE + HITLS_TICKET_KEY_SIZE)) { return HITLS_NULL_INPUT; } return SESSMGR_SetTicketKey(config->sessMgr, key, keySize); } #endif #if defined(HITLS_TLS_FEATURE_CERT_MODE) && defined(HITLS_TLS_FEATURE_RENEGOTIATION) int32_t HITLS_CFG_SetClientOnceVerifySupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportClientOnceVerify = support; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetClientOnceVerifySupport(HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportClientOnceVerify; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_ALL int32_t HITLS_CFG_GetMaxVersion(const HITLS_Config *config, uint16_t *maxVersion) { if (config == NULL || maxVersion == NULL) { return HITLS_NULL_INPUT; } *maxVersion = config->maxVersion; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetMinVersion(const HITLS_Config *config, uint16_t *minVersion) { if (config == NULL || minVersion == NULL) { return HITLS_NULL_INPUT; } *minVersion = config->minVersion; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_ALPN static int32_t AlpnListValidationCheck(const uint8_t *alpnList, uint32_t alpnProtosLen) { uint32_t index = 0u; while (index < alpnProtosLen) { if (alpnList[index] == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16608, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "alpnList null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } index += (alpnList[index] + 1); } if (index != alpnProtosLen) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16609, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "alpnProtosLen err", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } return HITLS_SUCCESS; } int32_t HITLS_CFG_SetAlpnProtos(HITLS_Config *config, const uint8_t *alpnProtos, uint32_t alpnProtosLen) { if (config == NULL) { return HITLS_NULL_INPUT; } /* If the input parameter is empty or the length is 0, clear the original alpn list */ if (alpnProtosLen == 0 || alpnProtos == NULL) { BSL_SAL_FREE(config->alpnList); config->alpnListSize = 0; return HITLS_SUCCESS; } /* Add the check on alpnList. The expected format is |protoLen1|proto1|protoLen2|proto2|...| */ if (AlpnListValidationCheck(alpnProtos, alpnProtosLen) != HITLS_SUCCESS) { return HITLS_CONFIG_INVALID_LENGTH; } uint8_t *alpnListTmp = (uint8_t *)BSL_SAL_Calloc(alpnProtosLen + 1, sizeof(uint8_t)); if (alpnListTmp == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16610, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(alpnListTmp, alpnProtosLen + 1, alpnProtos, alpnProtosLen); BSL_SAL_FREE(config->alpnList); config->alpnList = alpnListTmp; /* Ignore ending 0s */ config->alpnListSize = alpnProtosLen; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetAlpnProtosSelectCb(HITLS_Config *config, HITLS_AlpnSelectCb callback, void *userData) { if (config == NULL) { return HITLS_NULL_INPUT; } config->alpnSelectCb = callback; config->alpnUserData = userData; return HITLS_SUCCESS; } #endif #if defined(HITLS_TLS_FEATURE_SESSION_ID) int32_t HITLS_CFG_SetSessionIdCtx(HITLS_Config *config, const uint8_t *sessionIdCtx, uint32_t len) { if (config == NULL) { return HITLS_NULL_INPUT; } if (len != 0 && memcpy_s(config->sessionIdCtx, sizeof(config->sessionIdCtx), sessionIdCtx, len) != EOK) { return HITLS_MEMCPY_FAIL; } /* The allowed value is 0 */ config->sessionIdCtxSize = len; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_SESSION int32_t HITLS_CFG_SetSessionCacheMode(HITLS_Config *config, HITLS_SESS_CACHE_MODE mode) { if (config == NULL || config->sessMgr == NULL) { return HITLS_NULL_INPUT; } SESSMGR_SetCacheMode(config->sessMgr, mode); return HITLS_SUCCESS; } int32_t HITLS_CFG_GetSessionCacheMode(HITLS_Config *config, HITLS_SESS_CACHE_MODE *mode) { if (config == NULL || config->sessMgr == NULL || mode == NULL) { return HITLS_NULL_INPUT; } *mode = SESSMGR_GetCacheMode(config->sessMgr); return HITLS_SUCCESS; } int32_t HITLS_CFG_SetSessionCacheSize(HITLS_Config *config, uint32_t size) { if (config == NULL || config->sessMgr == NULL) { return HITLS_NULL_INPUT; } SESSMGR_SetCacheSize(config->sessMgr, size); return HITLS_SUCCESS; } int32_t HITLS_CFG_GetSessionCacheSize(HITLS_Config *config, uint32_t *size) { if (config == NULL || config->sessMgr == NULL || size == NULL) { return HITLS_NULL_INPUT; } *size = SESSMGR_GetCacheSize(config->sessMgr); return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_ALL int32_t HITLS_CFG_GetVersionSupport(const HITLS_Config *config, uint32_t *version) { if ((config == NULL) || (version == NULL)) { return HITLS_NULL_INPUT; } *version = config->version; return HITLS_SUCCESS; } static void ChangeSupportVersion(HITLS_Config *config) { uint32_t versionMask = config->version; uint32_t originVersionMask = config->originVersionMask; config->maxVersion = 0; config->minVersion = 0; /* The original supported version is disabled. This is abnormal and packets cannot be sent */ if ((versionMask & originVersionMask) == 0) { return; } /* Currently, only DTLS1.2 is supported. DTLS1.0 is not supported */ if ((versionMask & DTLS12_VERSION_BIT) == DTLS12_VERSION_BIT) { config->maxVersion = HITLS_VERSION_DTLS12; config->minVersion = HITLS_VERSION_DTLS12; return; } /* Description TLS_ANY_VERSION */ uint32_t versionBits[] = {TLS12_VERSION_BIT, TLS13_VERSION_BIT}; uint16_t versions[] = {HITLS_VERSION_TLS12, HITLS_VERSION_TLS13}; uint32_t versionBitsSize = sizeof(versionBits) / sizeof(uint32_t); for (uint32_t i = 0; i < versionBitsSize; i++) { if ((versionMask & versionBits[i]) == versionBits[i]) { config->maxVersion = versions[i]; if (config->minVersion == 0) { config->minVersion = versions[i]; } } } } int32_t HITLS_CFG_SetVersionSupport(HITLS_Config *config, uint32_t version) { if (config == NULL) { return HITLS_NULL_INPUT; } if ((version & SSLV3_VERSION_BIT) == SSLV3_VERSION_BIT) { return HITLS_CONFIG_INVALID_VERSION; } config->version = version; /* Update the maximum supported version */ ChangeSupportVersion(config); return HITLS_SUCCESS; } int32_t HITLS_SetVersion(HITLS_Ctx *ctx, uint32_t minVersion, uint32_t maxVersion) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetVersion(&(ctx->config.tlsConfig), (uint16_t)minVersion, (uint16_t)maxVersion); } int32_t HITLS_SetVersionForbid(HITLS_Ctx *ctx, uint32_t noVersion) { if (ctx == NULL) { return HITLS_NULL_INPUT; } return HITLS_CFG_SetVersionForbid(&(ctx->config.tlsConfig), noVersion); } #endif int32_t HITLS_CFG_SetQuietShutdown(HITLS_Config *config, int32_t mode) { if (config == NULL) { return HITLS_NULL_INPUT; } /* The value 0 indicates that the quiet disconnection mode is disabled. The value 1 indicates that the quiet * disconnection mode is enabled. */ if (mode != 0 && mode != 1) { return HITLS_CONFIG_INVALID_SET; } if (mode == 0) { config->isQuietShutdown = false; } else { config->isQuietShutdown = true; } return HITLS_SUCCESS; } int32_t HITLS_CFG_GetQuietShutdown(const HITLS_Config *config, int32_t *mode) { if (config == NULL || mode == NULL) { return HITLS_NULL_INPUT; } *mode = (int32_t)config->isQuietShutdown; return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HITLS_CFG_SetDtlsPostHsTimeoutVal(HITLS_Config *config, uint32_t timeoutVal) { if (config == NULL) { return HITLS_NULL_INPUT; } config->dtlsPostHsTimeoutVal = timeoutVal; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_SUITE_CIPHER_CBC int32_t HITLS_CFG_SetEncryptThenMac(HITLS_Config *config, uint32_t encryptThenMacType) { if (config == NULL) { return HITLS_NULL_INPUT; } if (encryptThenMacType == 0) { config->isEncryptThenMac = false; } else { config->isEncryptThenMac = true; } return HITLS_SUCCESS; } int32_t HITLS_CFG_GetEncryptThenMac(const HITLS_Config *config, uint32_t *encryptThenMacType) { if (config == NULL || encryptThenMacType == NULL) { return HITLS_NULL_INPUT; } *encryptThenMacType = (uint32_t)config->isEncryptThenMac; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_DTLS int32_t HITLS_CFG_IsDtls(const HITLS_Config *config, uint8_t *isDtls) { if (config == NULL || isDtls == NULL) { return HITLS_NULL_INPUT; } *isDtls = ((config->originVersionMask & DTLS12_VERSION_BIT) != 0); return HITLS_SUCCESS; } #endif int32_t HITLS_CFG_SetCipherServerPreference(HITLS_Config *config, bool isSupport) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportServerPreference = isSupport; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetCipherServerPreference(const HITLS_Config *config, bool *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = config->isSupportServerPreference; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_SESSION_TICKET int32_t HITLS_CFG_SetTicketNums(HITLS_Config *config, uint32_t ticketNums) { if (config == NULL) { return HITLS_NULL_INPUT; } config->ticketNums = ticketNums; return HITLS_SUCCESS; } uint32_t HITLS_CFG_GetTicketNums(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } return config->ticketNums; } #endif #ifdef HITLS_TLS_FEATURE_FLIGHT int32_t HITLS_CFG_SetFlightTransmitSwitch(HITLS_Config *config, uint8_t isEnable) { if (config == NULL) { return HITLS_NULL_INPUT; } if (isEnable == 0) { config->isFlightTransmitEnable = false; } else { config->isFlightTransmitEnable = true; } return HITLS_SUCCESS; } int32_t HITLS_CFG_GetFlightTransmitSwitch(const HITLS_Config *config, uint8_t *isEnable) { if (config == NULL || isEnable == NULL) { return HITLS_NULL_INPUT; } *isEnable = config->isFlightTransmitEnable; return HITLS_SUCCESS; } #endif #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) int32_t HITLS_CFG_SetDtlsCookieExchangeSupport(HITLS_Config *config, bool isSupport) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportDtlsCookieExchange = isSupport; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetDtlsCookieExchangeSupport(const HITLS_Config *config, bool *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = config->isSupportDtlsCookieExchange; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_MAINTAIN_KEYLOG int32_t HITLS_CFG_SetKeyLogCb(HITLS_Config *config, HITLS_KeyLogCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } config->keyLogCb = callback; return HITLS_SUCCESS; } HITLS_KeyLogCb HITLS_CFG_GetKeyLogCb(HITLS_Config *config) { if (config == NULL) { return NULL; } return config->keyLogCb; } #endif int32_t HITLS_CFG_SetEmptyRecordsNum(HITLS_Config *config, uint32_t emptyNum) { if (config == NULL) { return HITLS_NULL_INPUT; } config->emptyRecordsNum = emptyNum; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetEmptyRecordsNum(const HITLS_Config *config, uint32_t *emptyNum) { if (config == NULL || emptyNum == NULL) { return HITLS_NULL_INPUT; } *emptyNum = config->emptyRecordsNum; return HITLS_SUCCESS; } #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT int32_t HITLS_CFG_SetMaxSendFragment(HITLS_Config *config, uint16_t maxSendFragment) { if (config == NULL) { return HITLS_NULL_INPUT; } if (maxSendFragment > MAX_PLAINTEXT_LEN || maxSendFragment < MIN_MAX_SEND_FRAGMENT) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } config->maxSendFragment = maxSendFragment; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetMaxSendFragment(const HITLS_Config *config, uint16_t *maxSendFragment) { if (config == NULL || maxSendFragment == NULL) { return HITLS_NULL_INPUT; } *maxSendFragment = config->maxSendFragment; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_REC_INBUFFER_SIZE int32_t HITLS_CFG_SetRecInbufferSize(HITLS_Config *config, uint32_t recInbufferSize) { if (config == NULL) { return HITLS_NULL_INPUT; } if (recInbufferSize > MAX_INBUFFER_SIZE || recInbufferSize < MIN_INBUFFER_SIZE) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_LENGTH); return HITLS_CONFIG_INVALID_LENGTH; } config->recInbufferSize = recInbufferSize; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetRecInbufferSize(const HITLS_Config *config, uint32_t *recInbufferSize) { if (config == NULL || recInbufferSize == NULL) { return HITLS_NULL_INPUT; } *recInbufferSize = config->recInbufferSize; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_TLS13 int32_t HITLS_CFG_SetMiddleBoxCompat(HITLS_Config *config, bool isMiddleBox) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isMiddleBoxCompat = isMiddleBox; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetMiddleBoxCompat(HITLS_Config *config, bool *isMiddleBox) { if (config == NULL || isMiddleBox == NULL) { return HITLS_NULL_INPUT; } *isMiddleBox = config->isMiddleBoxCompat; return HITLS_SUCCESS; } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config.c
C
unknown
66,337
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdlib.h> #include <string.h> #include "securec.h" #include "hitls_build.h" #include "bsl_err_internal.h" #include "bsl_list.h" #include "tls_binlog_id.h" #include "hitls_error.h" #include "hitls_type.h" #include "hitls_cert_type.h" #include "tls_config.h" #include "cert_method.h" #include "cert_mgr.h" #include "cert.h" #include "cert_mgr.h" #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #define MAX_PATH_LEN 4096 #ifdef HITLS_TLS_FEATURE_SECURITY static int32_t CheckCertSecuritylevel(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isCACert) { CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16550, "unregistered callback"); } HITLS_CERT_Key *pubkey = NULL; int32_t ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_PUB_KEY, NULL, (void *)&pubkey); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16551, "GET_PUB_KEY fail"); } do { int32_t secBits = 0; ret = SAL_CERT_KeyCtrl(config, pubkey, CERT_KEY_CTRL_GET_SECBITS, NULL, (void *)&secBits); if (ret != HITLS_SUCCESS) { break; } if (isCACert == true) { ret = SECURITY_CfgCheck(config, HITLS_SECURITY_SECOP_CA_KEY, secBits, 0, cert); if (ret != SECURITY_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16552, "CfgCheck fail"); ret = HITLS_CERT_ERR_CA_KEY_WITH_INSECURE_SECBITS; break; } } else { ret = SECURITY_CfgCheck(config, HITLS_SECURITY_SECOP_EE_KEY, secBits, 0, cert); if (ret != SECURITY_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16553, "CfgCheck fail"); ret = HITLS_CERT_ERR_EE_KEY_WITH_INSECURE_SECBITS; break; } } int32_t signAlg = 0; ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_SIGN_ALGO, NULL, (void *)&signAlg); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16554, "GET_SIGN_ALGO fail"); break; } ret = SECURITY_CfgCheck(config, HITLS_SECURITY_SECOP_SIGALG_CHECK, 0, signAlg, NULL); if (ret != SECURITY_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16555, "CfgCheck fail"); ret = HITLS_CERT_ERR_INSECURE_SIG_ALG; break; } ret = HITLS_SUCCESS; } while (false); SAL_CERT_KeyFree(mgrCtx, pubkey); return ret; } #endif int32_t HITLS_CFG_SetVerifyStore(HITLS_Config *config, HITLS_CERT_Store *store, bool isClone) { if (config == NULL) { return HITLS_NULL_INPUT; } HITLS_CERT_Store *newStore = NULL; if (isClone && store != NULL) { newStore = SAL_CERT_StoreDup(config->certMgrCtx, store); if (newStore == NULL) { return HITLS_CERT_ERR_STORE_DUP; } } else { newStore = store; } int32_t ret = SAL_CERT_SetVerifyStore(config->certMgrCtx, newStore); if (ret != HITLS_SUCCESS) { if (isClone && newStore != NULL) { SAL_CERT_StoreFree(config->certMgrCtx, newStore); } } return ret; } HITLS_CERT_Store *HITLS_CFG_GetVerifyStore(const HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetVerifyStore(config->certMgrCtx); } int32_t HITLS_CFG_SetChainStore(HITLS_Config *config, HITLS_CERT_Store *store, bool isClone) { if (config == NULL) { return HITLS_NULL_INPUT; } HITLS_CERT_Store *newStore = NULL; if (isClone && store != NULL) { newStore = SAL_CERT_StoreDup(config->certMgrCtx, store); if (newStore == NULL) { return HITLS_CERT_ERR_STORE_DUP; } } else { newStore = store; } int32_t ret = SAL_CERT_SetChainStore(config->certMgrCtx, newStore); if (ret != HITLS_SUCCESS) { if (isClone && newStore != NULL) { SAL_CERT_StoreFree(config->certMgrCtx, newStore); } } return ret; } HITLS_CERT_Store *HITLS_CFG_GetChainStore(const HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetChainStore(config->certMgrCtx); } int32_t HITLS_CFG_SetCertStore(HITLS_Config *config, HITLS_CERT_Store *store, bool isClone) { if (config == NULL) { return HITLS_NULL_INPUT; } HITLS_CERT_Store *newStore = NULL; if (isClone && store != NULL) { newStore = SAL_CERT_StoreDup(config->certMgrCtx, store); if (newStore == NULL) { return HITLS_CERT_ERR_STORE_DUP; } } else { newStore = store; } int32_t ret = SAL_CERT_SetCertStore(config->certMgrCtx, newStore); if (ret != HITLS_SUCCESS) { if (isClone && newStore != NULL) { SAL_CERT_StoreFree(config->certMgrCtx, newStore); } } return ret; } HITLS_CERT_Store *HITLS_CFG_GetCertStore(const HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetCertStore(config->certMgrCtx); } int32_t HITLS_CFG_SetDefaultPasswordCb(HITLS_Config *config, HITLS_PasswordCb cb) { if (config == NULL) { return HITLS_NULL_INPUT; } return SAL_CERT_SetDefaultPasswordCb(config->certMgrCtx, cb); } HITLS_PasswordCb HITLS_CFG_GetDefaultPasswordCb(HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetDefaultPasswordCb(config->certMgrCtx); } int32_t HITLS_CFG_SetDefaultPasswordCbUserdata(HITLS_Config *config, void *userdata) { if (config == NULL) { return HITLS_NULL_INPUT; } return SAL_CERT_SetDefaultPasswordCbUserdata(config->certMgrCtx, userdata); } void *HITLS_CFG_GetDefaultPasswordCbUserdata(HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetDefaultPasswordCbUserdata(config->certMgrCtx); } static int32_t CFG_SetCertificate(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isClone, bool isTlcpEncCert) { if (config == NULL || cert == NULL) { return HITLS_NULL_INPUT; } HITLS_CERT_X509 *newCert = cert; if (isClone) { newCert = SAL_CERT_X509Dup(config->certMgrCtx, cert); if (newCert == NULL) { return HITLS_CERT_ERR_X509_DUP; } } int32_t ret = SAL_CERT_SetCurrentCert(config, newCert, isTlcpEncCert); if (ret != HITLS_SUCCESS) { if (isClone) { SAL_CERT_X509Free(newCert); } } return ret; } int32_t HITLS_CFG_SetCertificate(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isClone) { if (config == NULL || cert == NULL || config->certMgrCtx == NULL) { return HITLS_NULL_INPUT; } #ifdef HITLS_TLS_FEATURE_SECURITY int32_t ret = CheckCertSecuritylevel(config, cert, false); if (ret != HITLS_SUCCESS) { return ret; } #endif return CFG_SetCertificate(config, cert, isClone, false); } #ifdef HITLS_TLS_CONFIG_CERT_LOAD_FILE int32_t HITLS_CFG_LoadCertFile(HITLS_Config *config, const char *file, HITLS_ParseFormat format) { if (config == NULL || file == NULL || strlen(file) == 0) { return HITLS_NULL_INPUT; } int32_t ret; HITLS_CERT_X509 *cert = SAL_CERT_X509Parse(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, (const uint8_t *)file, (uint32_t)strlen(file), TLS_PARSE_TYPE_FILE, format); if (cert == NULL) { return HITLS_CFG_ERR_LOAD_CERT_FILE; } #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertSecuritylevel(config, cert, false); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); return ret; } #endif ret = SAL_CERT_SetCurrentCert(config, cert, false); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); } return ret; } #endif /* HITLS_TLS_CONFIG_CERT_LOAD_FILE */ int32_t HITLS_CFG_LoadCertBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format) { if (config == NULL || buf == NULL || bufLen == 0) { return HITLS_NULL_INPUT; } HITLS_CERT_X509 *newCert = SAL_CERT_X509Parse(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config),config, buf, bufLen, TLS_PARSE_TYPE_BUFF, format); if (newCert == NULL) { return HITLS_CFG_ERR_LOAD_CERT_BUFFER; } int ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertSecuritylevel(config, newCert, false); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(newCert); return ret; } #endif ret = SAL_CERT_SetCurrentCert(config, newCert, false); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(newCert); } return ret; } HITLS_CERT_X509 *HITLS_CFG_GetCertificate(const HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetCurrentCert(config->certMgrCtx); } static int32_t CFG_SetPrivateKey(HITLS_Config *config, HITLS_CERT_Key *privateKey, bool isClone, bool isTlcpEncCertPriKey) { if (config == NULL || privateKey == NULL) { return HITLS_NULL_INPUT; } HITLS_CERT_Key *newKey = NULL; if (isClone) { newKey = SAL_CERT_KeyDup(config->certMgrCtx, privateKey); if (newKey == NULL) { return HITLS_CERT_ERR_X509_DUP; } } else { newKey = privateKey; } int32_t ret = SAL_CERT_SetCurrentPrivateKey(config, newKey, isTlcpEncCertPriKey); if (ret != HITLS_SUCCESS) { if (isClone) { SAL_CERT_KeyFree(config->certMgrCtx, newKey); } } return ret; } #ifdef HITLS_TLS_PROTO_TLCP11 int32_t HITLS_CFG_SetTlcpPrivateKey(HITLS_Config *config, HITLS_CERT_Key *privateKey, bool isClone, bool isTlcpEncCertPriKey) { return CFG_SetPrivateKey(config, privateKey, isClone, isTlcpEncCertPriKey); } int32_t HITLS_CFG_SetTlcpCertificate(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isClone, bool isTlcpEncCert) { return CFG_SetCertificate(config, cert, isClone, isTlcpEncCert); } #endif int32_t HITLS_CFG_SetPrivateKey(HITLS_Config *config, HITLS_CERT_Key *privateKey, bool isClone) { return CFG_SetPrivateKey(config, privateKey, isClone, false); } #ifdef HITLS_TLS_CONFIG_CERT_LOAD_FILE int32_t HITLS_CFG_ProviderLoadKeyFile(HITLS_Config *config, const char *file, const char *format, const char *type) { if (config == NULL || file == NULL || strlen(file) == 0) { return HITLS_NULL_INPUT; } HITLS_CERT_Key *newKey = SAL_CERT_KeyParse(config, (const uint8_t *)file, (uint32_t)strlen(file), TLS_PARSE_TYPE_FILE, format, type); if (newKey == NULL) { return HITLS_CFG_ERR_LOAD_KEY_FILE; } int32_t ret = SAL_CERT_SetCurrentPrivateKey(config, newKey, false); if (ret != HITLS_SUCCESS) { SAL_CERT_KeyFree(config->certMgrCtx, newKey); } return ret; } int32_t HITLS_CFG_LoadKeyFile(HITLS_Config *config, const char *file, HITLS_ParseFormat format) { if (config == NULL || file == NULL || strlen(file) == 0) { return HITLS_NULL_INPUT; } HITLS_CERT_Key *newKey = SAL_CERT_KeyParse(config, (const uint8_t *)file, (uint32_t)strlen(file), TLS_PARSE_TYPE_FILE, SAL_CERT_GetParseFormatStr(format), NULL); if (newKey == NULL) { return HITLS_CFG_ERR_LOAD_KEY_FILE; } int32_t ret = SAL_CERT_SetCurrentPrivateKey(config, newKey, false); if (ret != HITLS_SUCCESS) { SAL_CERT_KeyFree(config->certMgrCtx, newKey); } return ret; } #endif /* HITLS_TLS_CONFIG_CERT_LOAD_FILE */ int32_t HITLS_CFG_ProviderLoadKeyBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, const char *format, const char *type) { if (config == NULL || buf == NULL || bufLen == 0) { return HITLS_NULL_INPUT; } HITLS_CERT_Key *newKey = SAL_CERT_KeyParse(config, buf, bufLen, TLS_PARSE_TYPE_BUFF, type, format); if (newKey == NULL) { return HITLS_CFG_ERR_LOAD_KEY_BUFFER; } int32_t ret = SAL_CERT_SetCurrentPrivateKey(config, newKey, false); if (ret != HITLS_SUCCESS) { SAL_CERT_KeyFree(config->certMgrCtx, newKey); } return ret; } int32_t HITLS_CFG_LoadKeyBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format) { if (config == NULL || buf == NULL || bufLen == 0) { return HITLS_NULL_INPUT; } HITLS_CERT_Key *newKey = SAL_CERT_KeyParse(config, buf, bufLen, TLS_PARSE_TYPE_BUFF, SAL_CERT_GetParseFormatStr(format), NULL); if (newKey == NULL) { return HITLS_CFG_ERR_LOAD_KEY_BUFFER; } int32_t ret = SAL_CERT_SetCurrentPrivateKey(config, newKey, false); if (ret != HITLS_SUCCESS) { SAL_CERT_KeyFree(config->certMgrCtx, newKey); } return ret; } HITLS_CERT_Key *HITLS_CFG_GetPrivateKey(HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetCurrentPrivateKey(config->certMgrCtx, false); } int32_t HITLS_CFG_CheckPrivateKey(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } CERT_MgrCtx *certMgrCtx = config->certMgrCtx; if (certMgrCtx == NULL) { /* If no certificate callback is registered, the certificate management module will not initialized. */ return HITLS_UNREGISTERED_CALLBACK; } HITLS_CERT_X509 *cert = SAL_CERT_GetCurrentCert(certMgrCtx); if (cert == NULL) { /* no certificate is added */ return HITLS_CONFIG_NO_CERT; } HITLS_CERT_Key *privateKey = SAL_CERT_GetCurrentPrivateKey(certMgrCtx, false); if (privateKey == NULL) { /* no private key is added */ return HITLS_CONFIG_NO_PRIVATE_KEY; } return SAL_CERT_CheckPrivateKey(config, cert, privateKey); } int32_t HITLS_CFG_AddChainCert(HITLS_Config *config, HITLS_CERT_X509 *cert, bool isClone) { if (config == NULL || cert == NULL || config->certMgrCtx == NULL) { return HITLS_NULL_INPUT; } int32_t ret = HITLS_SUCCESS; #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertSecuritylevel(config, cert, true); if (ret != HITLS_SUCCESS) { return ret; } #endif HITLS_CERT_X509 *newCert = cert; if (isClone) { newCert = SAL_CERT_X509Dup(config->certMgrCtx, cert); if (newCert == NULL) { return HITLS_CERT_ERR_X509_DUP; } } ret = SAL_CERT_AddChainCert(config->certMgrCtx, newCert); if (ret != HITLS_SUCCESS) { if (isClone) { SAL_CERT_X509Free(newCert); } } return ret; } int32_t HITLS_CFG_AddCertToStore(HITLS_Config *config, HITLS_CERT_X509 *cert, HITLS_CERT_StoreType storeType, bool isClone) { if (config == NULL || cert == NULL) { BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } HITLS_CERT_Store *store = NULL; switch (storeType) { case TLS_CERT_STORE_TYPE_DEFAULT: store = SAL_CERT_GetCertStore(config->certMgrCtx); break; case TLS_CERT_STORE_TYPE_VERIFY: store = SAL_CERT_GetVerifyStore(config->certMgrCtx); break; case TLS_CERT_STORE_TYPE_CHAIN: store = SAL_CERT_GetChainStore(config->certMgrCtx); break; default: return HITLS_CERT_ERR_INVALID_STORE_TYPE; } HITLS_CERT_X509 *newCert = cert; if (isClone) { newCert = SAL_CERT_X509Dup(config->certMgrCtx, cert); if (newCert == NULL) { return HITLS_CERT_ERR_X509_DUP; } } int32_t ret = SAL_CERT_StoreCtrl(config, store, CERT_STORE_CTRL_ADD_CERT_LIST, newCert, NULL); if (ret != HITLS_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); if (isClone) { SAL_CERT_X509Free(newCert); } } return ret; } HITLS_CERT_X509 *HITLS_CFG_ParseCert(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { if (config == NULL || buf == NULL || len == 0) { return NULL; } HITLS_CERT_X509 *newCert = SAL_CERT_X509Parse(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, buf, len, type, format); if (newCert == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17158, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "X509Parse fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CFG_ERR_LOAD_CERT_BUFFER); return NULL; } return newCert; } HITLS_CERT_Key *HITLS_CFG_ProviderParseKey(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, const char *format, const char *encodeType) { if (config == NULL || buf == NULL || len == 0) { return NULL; } HITLS_CERT_Key *newKey = SAL_CERT_KeyParse(config, buf, len, type, format, encodeType); if (newKey == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17165, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Provider KeyParse fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CFG_ERR_LOAD_KEY_BUFFER); return NULL; } return newKey; } HITLS_CERT_Key *HITLS_CFG_ParseKey(HITLS_Config *config, const uint8_t *buf, uint32_t len, HITLS_ParseType type, HITLS_ParseFormat format) { if (config == NULL || buf == NULL || len == 0) { return NULL; } HITLS_CERT_Key *newKey = SAL_CERT_KeyParse(config, buf, len, type, SAL_CERT_GetParseFormatStr(format), NULL); if (newKey == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17164, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "KeyParse fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CFG_ERR_LOAD_KEY_BUFFER); return NULL; } return newKey; } HITLS_CERT_Chain *HITLS_CFG_GetChainCerts(HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetCurrentChainCerts(config->certMgrCtx); } int32_t HITLS_CFG_ClearChainCerts(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } SAL_CERT_ClearCurrentChainCerts(config->certMgrCtx); return HITLS_SUCCESS; } int32_t HITLS_CFG_AddExtraChainCert(HITLS_Config *config, HITLS_CERT_X509 *cert) { if (config == NULL || cert == NULL) { return HITLS_NULL_INPUT; } return SAL_CERT_AddExtraChainCert(config->certMgrCtx, cert); } HITLS_CERT_Chain *HITLS_CFG_GetExtraChainCerts(HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetExtraChainCerts(config->certMgrCtx, false); } int32_t HITLS_CFG_ClearExtraChainCerts(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } SAL_CERT_ClearExtraChainCerts(config->certMgrCtx); return HITLS_SUCCESS; } int32_t HITLS_CFG_RemoveCertAndKey(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } SAL_CERT_ClearCertAndKey(config->certMgrCtx); return HITLS_SUCCESS; } int32_t HITLS_CFG_SetVerifyCb(HITLS_Config *config, HITLS_VerifyCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } return SAL_CERT_SetVerifyCb(config->certMgrCtx, callback); } HITLS_VerifyCb HITLS_CFG_GetVerifyCb(HITLS_Config *config) { if (config == NULL) { return NULL; } return SAL_CERT_GetVerifyCb(config->certMgrCtx); } #ifdef HITLS_TLS_FEATURE_CERT_CB int32_t HITLS_CFG_SetCertCb(HITLS_Config *config, HITLS_CertCb certCb, void *arg) { if (config == NULL) { return HITLS_NULL_INPUT; } return SAL_CERT_SetCertCb(config->certMgrCtx, certCb, arg); } #endif /* HITLS_TLS_FEATURE_CERT_CB */ #ifdef HITLS_TLS_FEATURE_CERT_MODE int32_t HITLS_CFG_SetVerifyNoneSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportVerifyNone = support; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetVerifyNoneSupport(HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportVerifyNone; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetClientVerifySupport(HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportClientVerify; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetNoClientCertSupport(HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportNoClientCert; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetClientVerifySupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportClientVerify = support; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetNoClientCertSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportNoClientCert = support; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES static void HitlsTrustedCANodeFree(void *caNode) { if (caNode == NULL) { return; } HITLS_TrustedCANode *newCaNode = (HITLS_TrustedCANode *)caNode; BSL_SAL_FREE(newCaNode->data); newCaNode->data = NULL; BSL_SAL_FREE(newCaNode); } void HITLS_CFG_ClearCAList(HITLS_Config *config) { if (config == NULL) { return; } BSL_LIST_FREE(config->caList, HitlsTrustedCANodeFree); config->caList = NULL; return; } int32_t HITLS_CFG_AddCAIndication(HITLS_Config *config, HITLS_TrustedCAType caType, const uint8_t *data, uint32_t len) { if ((config == NULL) || (data == NULL) || (len == 0)) { return HITLS_NULL_INPUT; } HITLS_TrustedCANode *newCaNode = BSL_SAL_Calloc(1u, sizeof(HITLS_TrustedCANode)); if (newCaNode == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16558, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } newCaNode->caType = caType; if (len >= UINT16_MAX) { BSL_SAL_FREE(newCaNode); return HITLS_CONFIG_INVALID_LENGTH; } newCaNode->data = BSL_SAL_Dump(data, len); if (newCaNode->data == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16559, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); BSL_SAL_FREE(newCaNode); return HITLS_MEMALLOC_FAIL; } newCaNode->dataSize = len; if (config->caList == NULL) { config->caList = BSL_LIST_New(sizeof(HITLS_TrustedCANode *)); if (config->caList == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16560, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "LIST_New fail", 0, 0, 0, 0); BSL_SAL_FREE(newCaNode->data); BSL_SAL_FREE(newCaNode); return HITLS_MEMALLOC_FAIL; } } /* tail insertion */ int32_t ret = (int32_t)BSL_LIST_AddElement((BslList *)config->caList, newCaNode, BSL_LIST_POS_END); if (ret != 0) { BSL_SAL_FREE(newCaNode->data); BSL_SAL_FREE(newCaNode); } return ret; } HITLS_TrustedCAList *HITLS_CFG_GetCAList(const HITLS_Config *config) { if (config == NULL) { return NULL; } return config->caList; } int32_t HITLS_CFG_SetCAList(HITLS_Config *config, HITLS_TrustedCAList *list) { if (config == NULL) { return HITLS_NULL_INPUT; } if (config->caList != NULL) { HITLS_CFG_ClearCAList(config); } config->caList = list; return HITLS_SUCCESS; } static int32_t ParseAndGetSubjectDN(HITLS_Config *config, const char *input, uint32_t len, HITLS_ParseFormat format, HITLS_ParseType type, BSL_Buffer *nodeBufferOut) { if (config == NULL || input == NULL || len == 0 || nodeBufferOut == NULL) { return HITLS_NULL_INPUT; } int32_t ret; HITLS_CERT_X509 *cert = SAL_CERT_X509Parse(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, (const uint8_t *)input, len, type, format); if (cert == NULL) { return HITLS_CFG_ERR_LOAD_CERT_FILE; } #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertSecuritylevel(config, cert, false); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); return ret; } #endif ret = SAL_CERT_X509Ctrl(config, cert, CERT_CTRL_GET_ENCODE_SUBJECT_DN, NULL, (void *)nodeBufferOut); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); return ret; } SAL_CERT_X509Free(cert); return HITLS_SUCCESS; } int32_t HITLS_CFG_ParseCAList(HITLS_Config *config, const char *input, uint32_t inputLen, HITLS_ParseType inputType, HITLS_ParseFormat format, HITLS_TrustedCAList **caList) { if (config == NULL || input == NULL || inputLen == 0) { return HITLS_NULL_INPUT; } int32_t ret; HITLS_TrustedCAList *list = NULL; HITLS_TrustedCANode *newCaNode = BSL_SAL_Calloc(1u, sizeof(HITLS_TrustedCANode)); if (newCaNode == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17367, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Calloc fail", 0, 0, 0, 0); ret = HITLS_MEMALLOC_FAIL; goto ERR; } BSL_Buffer nodeBuffer = {0}; ret = ParseAndGetSubjectDN(config, input, inputLen, format, inputType, &nodeBuffer); if (ret != HITLS_SUCCESS) { goto ERR; } newCaNode->caType = HITLS_TRUSTED_CA_X509_NAME; newCaNode->data = nodeBuffer.data; newCaNode->dataSize = nodeBuffer.dataLen; list = BSL_LIST_New(sizeof(HITLS_TrustedCANode *)); if (list == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID17366, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "LIST_New fail", 0, 0, 0, 0); ret = HITLS_MEMALLOC_FAIL; goto ERR; } ret = BSL_LIST_AddElement(list, newCaNode, BSL_LIST_POS_END); if (ret != BSL_SUCCESS) { goto ERR; } *caList = list; return ret; ERR: BSL_LIST_FREE(list, HitlsTrustedCANodeFree); if (newCaNode != NULL) { BSL_SAL_Free(newCaNode->data); } BSL_SAL_Free(newCaNode); return ret; } #endif /* HITLS_TLS_FEATURE_CERTIFICATE_AUTHORITIES */ #ifdef HITLS_TLS_CONFIG_CERT_BUILD_CHAIN static void FreeCertList(HITLS_CERT_X509 **certList, uint32_t certNum) { if (certList == NULL) { return; } for (uint32_t i = 0; i < certNum; i++) { SAL_CERT_X509Free(certList[i]); } } static int32_t CFG_BuildCertChain(HITLS_Config *config, HITLS_CERT_Store *store, HITLS_CERT_X509 *cert, HITLS_BUILD_CHAIN_FLAG flag) { CERT_MgrCtx *mgrCtx = config->certMgrCtx; HITLS_CERT_X509 *certList[TLS_DEFAULT_VERIFY_DEPTH] = {0}; uint32_t certNum = TLS_DEFAULT_VERIFY_DEPTH; int32_t ret = SAL_CERT_BuildChain(config, store, cert, certList, &certNum); if (ret != HITLS_SUCCESS) { return ret; } if (flag & HITLS_BUILD_CHAIN_FLAG_NO_ROOT) { if (certNum > 0) { bool isSelfSigned = false; ret = SAL_CERT_X509Ctrl(config, certList[certNum - 1], CERT_CTRL_IS_SELF_SIGNED, NULL, (void *)&isSelfSigned); if (ret != HITLS_SUCCESS) { FreeCertList(certList, certNum); return ret; } if (isSelfSigned) { SAL_CERT_X509Free(certList[certNum - 1]); certNum--; } } } #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertSecuritylevel(config, cert, false); if (ret != HITLS_SUCCESS) { FreeCertList(certList, certNum); return ret; } #endif SAL_CERT_ClearCurrentChainCerts(mgrCtx); for (uint32_t i = 1; i < certNum; i++) { #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertSecuritylevel(config, certList[i], true); if (ret != HITLS_SUCCESS) { FreeCertList(certList, certNum); return ret; } #endif HITLS_CERT_X509 *tempCert = SAL_CERT_X509Ref(mgrCtx, certList[i]); ret = SAL_CERT_AddChainCert(mgrCtx, tempCert); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(tempCert); FreeCertList(certList, certNum); return ret; } } FreeCertList(certList, certNum); return HITLS_SUCCESS; } int32_t HITLS_CFG_BuildCertChain(HITLS_Config *config, HITLS_BUILD_CHAIN_FLAG flag) { if (config == NULL || config->certMgrCtx == NULL) { return HITLS_NULL_INPUT; } CERT_MgrCtx *mgrCtx = config->certMgrCtx; int32_t ret = HITLS_SUCCESS; HITLS_CERT_X509 *cert = SAL_CERT_GetCurrentCert(mgrCtx); if (cert == NULL) { /* no certificate is added */ return HITLS_CONFIG_NO_CERT; } HITLS_CERT_Store *store = NULL; if (flag & HITLS_BUILD_CHAIN_FLAG_CHECK) { HITLS_CERT_Chain *chainCertList = SAL_CERT_GetCurrentChainCerts(mgrCtx); if (chainCertList == NULL) { return HITLS_SUCCESS; } store = SAL_CERT_StoreNew(mgrCtx); if (store == NULL) { return HITLS_MEMALLOC_FAIL; } HITLS_CERT_X509 *tempCert = (HITLS_CERT_X509 *)BSL_LIST_GET_FIRST(chainCertList); while (tempCert != NULL) { HITLS_CERT_X509 *refCert = SAL_CERT_X509Ref(mgrCtx, tempCert); ret = SAL_CERT_StoreCtrl(config, store, CERT_STORE_CTRL_ADD_CERT_LIST, refCert, NULL); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(refCert); SAL_CERT_StoreFree(mgrCtx, store); return ret; } tempCert = (HITLS_CERT_X509 *)BSL_LIST_GET_NEXT(chainCertList); } } else { HITLS_CERT_Store *chainStore = SAL_CERT_GetChainStore(mgrCtx); HITLS_CERT_Store *certStore = SAL_CERT_GetCertStore(mgrCtx); store = (chainStore != NULL) ? chainStore : certStore; if (store == NULL) { SAL_CERT_ClearCurrentChainCerts(mgrCtx); return HITLS_SUCCESS; } } ret = CFG_BuildCertChain(config, store, cert, flag); if (flag & HITLS_BUILD_CHAIN_FLAG_CHECK) { SAL_CERT_StoreFree(mgrCtx, store); } return ret; } #endif int32_t HITLS_CFG_CtrlSetVerifyParams( HITLS_Config *config, HITLS_CERT_Store *store, uint32_t cmd, int64_t in, void *inArg) { if (config == NULL) { return HITLS_NULL_INPUT; } if (inArg == NULL) { return SAL_CERT_CtrlVerifyParams(config, store, cmd, &in, NULL); } return SAL_CERT_CtrlVerifyParams(config, store, cmd, inArg, NULL); } int32_t HITLS_CFG_CtrlGetVerifyParams(HITLS_Config *config, HITLS_CERT_Store *store, uint32_t cmd, void *out) { if (config == NULL || out == NULL) { return HITLS_NULL_INPUT; } return SAL_CERT_CtrlVerifyParams(config, store, cmd, NULL, out); } static int32_t LoadCrlCommon(HITLS_Config *config, const uint8_t *data, uint32_t dataLen, HITLS_ParseType parseType, HITLS_ParseFormat format, uint32_t crlParseFailErr) { if (config == NULL) { return HITLS_NULL_INPUT; } CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16566, "unregistered callback"); } HITLS_CERT_CRLList *crlList = SAL_CERT_CrlParse(config, data, dataLen, parseType, format); if (crlList == NULL) { return crlParseFailErr; } HITLS_CERT_Store *certStore = SAL_CERT_GetVerifyStore(mgrCtx) == NULL ? SAL_CERT_GetCertStore(mgrCtx) : SAL_CERT_GetVerifyStore(mgrCtx); if (certStore == NULL) { SAL_CERT_CrlFree(crlList); return RETURN_ERROR_NUMBER_PROCESS(HITLS_CONFIG_NO_CERT, BINLOG_ID16567, "store is null"); } int32_t ret = SAL_CERT_StoreCtrl(config, certStore, CERT_STORE_CTRL_ADD_CRL_LIST, crlList, NULL); SAL_CERT_CrlFree(crlList); return ret; } int32_t HITLS_CFG_LoadCrlFile(HITLS_Config *config, const char *file, HITLS_ParseFormat format) { if (file == NULL || strlen(file) == 0) { return HITLS_NULL_INPUT; } return LoadCrlCommon(config, (const uint8_t *)file, (uint32_t)strlen(file), TLS_PARSE_TYPE_FILE, format, HITLS_CFG_ERR_LOAD_CRL_FILE); } int32_t HITLS_CFG_LoadCrlBuffer(HITLS_Config *config, const uint8_t *buf, uint32_t bufLen, HITLS_ParseFormat format) { if (buf == NULL || bufLen == 0) { return HITLS_NULL_INPUT; } return LoadCrlCommon(config, buf, bufLen, TLS_PARSE_TYPE_BUFF, format, HITLS_CFG_ERR_LOAD_CRL_BUFFER); } int32_t HITLS_CFG_ClearVerifyCrls(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } CERT_MgrCtx *mgrCtx = config->certMgrCtx; if (mgrCtx == NULL) { return RETURN_ERROR_NUMBER_PROCESS(HITLS_UNREGISTERED_CALLBACK, BINLOG_ID16569, "unregistered callback"); } HITLS_CERT_Store *certStore = SAL_CERT_GetCertStore(mgrCtx); if (certStore == NULL) { return HITLS_SUCCESS; /* No store, nothing to clear */ } return SAL_CERT_StoreCtrl(config, certStore, CERT_STORE_CTRL_CLEAR_CRL_LIST, NULL, NULL); } #ifdef HITLS_TLS_CONFIG_CERT_LOAD_FILE int32_t HITLS_CFG_UseCertificateChainFile(HITLS_Config *config, const char *file) { if (config == NULL || file == NULL) { return HITLS_NULL_INPUT; } int32_t ret = HITLS_SUCCESS; HITLS_CERT_Chain *certList = SAL_CERT_X509ParseBundleFile(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, (const uint8_t *)file, (uint32_t)strlen(file), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (certList == NULL) { return HITLS_CFG_ERR_LOAD_CERT_FILE; } HITLS_CERT_X509 *tempCert = (HITLS_CERT_X509 *)BSL_LIST_GET_FIRST(certList); if (tempCert == NULL) { SAL_CERT_ChainFree(certList); return HITLS_CFG_ERR_LOAD_CERT_FILE; } ret = HITLS_CFG_SetCertificate(config, tempCert, true); if (ret != HITLS_SUCCESS) { SAL_CERT_ChainFree(certList); return ret; } tempCert = (HITLS_CERT_X509 *)BSL_LIST_GET_NEXT(certList); if (tempCert != NULL) { ret = HITLS_CFG_ClearChainCerts(config); if (ret != HITLS_SUCCESS) { SAL_CERT_ChainFree(certList); return ret; } } while (tempCert != NULL) { ret = HITLS_CFG_AddChainCert(config, tempCert, true); if (ret != HITLS_SUCCESS) { SAL_CERT_ChainFree(certList); return ret; } tempCert = (HITLS_CERT_X509 *)BSL_LIST_GET_NEXT(certList); } SAL_CERT_ChainFree(certList); return ret; } int32_t HITLS_CFG_LoadVerifyFile(HITLS_Config *config, const char *file) { if (config == NULL || file == NULL || strlen(file) == 0 || config->certMgrCtx == NULL) { return HITLS_NULL_INPUT; } int32_t ret; HITLS_CERT_X509 *cert = SAL_CERT_X509Parse(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config), config, (const uint8_t *)file, (uint32_t)strlen(file), TLS_PARSE_TYPE_FILE, TLS_PARSE_FORMAT_PEM); if (cert == NULL) { return HITLS_CFG_ERR_LOAD_CERT_FILE; } #ifdef HITLS_TLS_FEATURE_SECURITY ret = CheckCertSecuritylevel(config, cert, false); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); return ret; } #endif HITLS_CERT_Store *store = SAL_CERT_GetCertStore(config->certMgrCtx); ret = SAL_CERT_StoreCtrl(config, store, CERT_STORE_CTRL_ADD_CERT_LIST, cert, NULL); if (ret != HITLS_SUCCESS) { SAL_CERT_X509Free(cert); BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif /* HITLS_TLS_CONFIG_CERT_LOAD_FILE */ static int32_t LoadVerifyDirAddPath(HITLS_Config *config, HITLS_CERT_Store *store, const char *start, size_t len) { if (start == NULL) { return HITLS_CONFIG_INVALID_LENGTH; } if (len == 0) { return HITLS_SUCCESS; /* nothing to add */ } if (len >= MAX_PATH_LEN) { return HITLS_CONFIG_INVALID_LENGTH; } char buf[MAX_PATH_LEN + 1] = {0}; if (memcpy_s(buf, sizeof(buf), start, len) != EOK) { return HITLS_MEMCPY_FAIL; } buf[len] = '\0'; return SAL_CERT_StoreCtrl(config, store, CERT_STORE_CTRL_ADD_CA_PATH, (void *)buf, NULL); } int32_t HITLS_CFG_LoadVerifyDir(HITLS_Config *config, const char *path) { if (config == NULL || path == NULL || strlen(path) == 0 || config->certMgrCtx == NULL) { return HITLS_NULL_INPUT; } HITLS_CERT_Store *store = SAL_CERT_GetCertStore(config->certMgrCtx); /* Single path without separator */ if (strchr(path, ':') == NULL) { return LoadVerifyDirAddPath(config, store, path, strlen(path)); } /* Multiple colon-separated paths */ int32_t ret = HITLS_SUCCESS; const char *start = path; const char *p = path; while (*p != '\0') { if (*p == ':') { uint32_t len = (uint32_t)(p - start); ret = LoadVerifyDirAddPath(config, store, start, len); if (ret != HITLS_SUCCESS) { return ret; } start = p + 1; } p++; } /* trailing segment */ if (start < p) { ret = LoadVerifyDirAddPath(config, store, start, (uint32_t)(p - start)); } return ret; } int32_t HITLS_CFG_FreeCert(HITLS_Config *config, HITLS_CERT_X509 *cert) { if (config == NULL || config->certMgrCtx == NULL) { return HITLS_NULL_INPUT; } SAL_CERT_X509Free(cert); return HITLS_SUCCESS; } int32_t HITLS_CFG_FreeKey(HITLS_Config *config, HITLS_CERT_Key *key) { if (config == NULL || config->certMgrCtx == NULL) { return HITLS_NULL_INPUT; } SAL_CERT_KeyFree(config->certMgrCtx, key); return HITLS_SUCCESS; }
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config_cert.c
C
unknown
38,730
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include <stdbool.h> #include <stdint.h> #include "hitls_build.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "hitls_crypt_type.h" #include "hitls_cert_type.h" #include "hitls_error.h" #include "hitls_config.h" #include "tls.h" #include "tls_config.h" #include "cipher_suite.h" #include "config_type.h" static bool CFG_IsValidVersion(uint16_t version) { switch (version) { case HITLS_VERSION_TLS12: case HITLS_VERSION_TLS13: case HITLS_VERSION_DTLS12: case HITLS_VERSION_TLCP_DTLCP11: return true; default: break; } return false; } static bool HaveMatchSignAlg(const TLS_Config *config, HITLS_AuthAlgo authAlg, const uint16_t *signatureAlgorithms, uint32_t signatureAlgorithmsSize) { HITLS_SignAlgo signAlg = HITLS_SIGN_BUTT; /** Traverse the signature algorithms. If the matching is successful, return true */ for (uint32_t i = 0u; i < signatureAlgorithmsSize; i++) { const TLS_SigSchemeInfo *info = ConfigGetSignatureSchemeInfo(config, signatureAlgorithms[i]); if (info == NULL) { continue; } signAlg = info->signAlgId; if (((signAlg == HITLS_SIGN_RSA_PKCS1_V15) || (signAlg == HITLS_SIGN_RSA_PSS)) && (authAlg == HITLS_AUTH_RSA)) { return true; } if (((signAlg == HITLS_SIGN_ECDSA) || (signAlg == HITLS_SIGN_ED25519)) && (authAlg == HITLS_AUTH_ECDSA)) { return true; } if (signAlg == HITLS_SIGN_DSA && authAlg == HITLS_AUTH_DSS) { return true; } if (signAlg == HITLS_SIGN_SM2 && authAlg == HITLS_AUTH_SM2) { return true; } } return false; } static int32_t CheckPointFormats(const TLS_Config *config) { if ((config->pointFormats == NULL) || (config->pointFormatsSize == 0)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16561, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "pointFormats null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_SET); return HITLS_CONFIG_INVALID_SET; } /** Currently, only one point format is supported */ if ((config->pointFormatsSize != 1) || (config->pointFormats[0] != HITLS_POINT_FORMAT_UNCOMPRESSED)) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_UNSUPPORT_POINT_FORMATS); return HITLS_CONFIG_UNSUPPORT_POINT_FORMATS; } return HITLS_SUCCESS; } static bool IsCipherSuiteValid(const TLS_Config *config, uint16_t cipherSuite) { if ((CFG_CheckCipherSuiteSupported(cipherSuite) != true) || (CFG_CheckCipherSuiteVersion(cipherSuite, config->minVersion, config->maxVersion) != true)) { /* The cipher suite must match the configured version */ return false; } return true; } static int32_t CheckSign(const TLS_Config *config) { uint16_t *signAlgorithms = config->signAlgorithms; uint32_t signAlgorithmsSize = config->signAlgorithmsSize; /** If the signature algorithm is empty, the default signature algorithm in the cipher suite is used and no further * check is required */ if ((signAlgorithms == NULL) || (signAlgorithmsSize == 0)) { return HITLS_SUCCESS; } /** Check the validity of the signature algorithms one by one */ for (uint32_t i = 0; i < signAlgorithmsSize; i++) { if (ConfigGetSignatureSchemeInfo(config, signAlgorithms[i]) == NULL) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_UNSUPPORT_SIGNATURE_ALGORITHM); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15779, BSL_LOG_LEVEL_FATAL, BSL_LOG_BINLOG_TYPE_RUN, "Unsupported signature algorithms: 0x%04x.", signAlgorithms[i], 0, 0, 0); return HITLS_CONFIG_UNSUPPORT_SIGNATURE_ALGORITHM; } } /* In this case, only the 1.3 cipher suite is configured, or only TLS1.3 is supported. The authentication algorithm is not specified in the TLS 1.3 cipher suite and therefore does not need to be checked. */ if (config->cipherSuitesSize == 0 || ((config->minVersion == HITLS_VERSION_TLS13) && (config->maxVersion == HITLS_VERSION_TLS13))) { return HITLS_SUCCESS; } /** Check the compatibility between the signature algorithm and the cipher suite */ for (uint32_t i = 0; i < config->cipherSuitesSize; i++) { CipherSuiteInfo info = {0}; if (IsCipherSuiteValid(config, config->cipherSuites[i]) == false) { continue; } (void)CFG_GetCipherSuiteInfo(config->cipherSuites[i], &info); /** PSK does not require the signature algorithm */ if ((info.kxAlg == HITLS_KEY_EXCH_PSK) || (info.kxAlg == HITLS_KEY_EXCH_DHE_PSK) || (info.kxAlg == HITLS_KEY_EXCH_ECDHE_PSK)) { return HITLS_SUCCESS; } /* Anon does not require the signature algorithm */ if (info.authAlg == HITLS_AUTH_NULL) { return HITLS_SUCCESS; } /** Check whether a signature algorithm matching the cipher suite exists */ if (HaveMatchSignAlg(config, info.authAlg, signAlgorithms, signAlgorithmsSize)) { return HITLS_SUCCESS; } } BSL_ERR_PUSH_ERROR(HITLS_CONFIG_NO_SUITABLE_SIGNATURE_ALGORITHM); return HITLS_CONFIG_NO_SUITABLE_SIGNATURE_ALGORITHM; } static bool IsHaveEccCipherSuite(const TLS_Config *config) { for (uint32_t i = 0u; i < config->cipherSuitesSize; i++) { CipherSuiteInfo info = {0}; if (IsCipherSuiteValid(config, config->cipherSuites[i]) == false) { continue; } (void)CFG_GetCipherSuiteInfo(config->cipherSuites[i], &info); /* The ECC cipher suite exists */ if ((info.authAlg == HITLS_AUTH_ECDSA) || (info.kxAlg == HITLS_KEY_EXCH_ECDHE) || (info.kxAlg == HITLS_KEY_EXCH_ECDH) || (info.kxAlg == HITLS_KEY_EXCH_ECDHE_PSK)) { return true; } } return false; } static int32_t CheckGroup(const TLS_Config *config) { if (config->groupsSize == 0u) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_NO_GROUPS); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15780, BSL_LOG_LEVEL_WARN, BSL_LOG_BINLOG_TYPE_RUN, "Set ecdhe cipher with no group id", 0, 0, 0, 0); return HITLS_CONFIG_NO_GROUPS; } return HITLS_SUCCESS; } int32_t CheckVersion(uint16_t minVersion, uint16_t maxVersion) { if ((CFG_IsValidVersion(minVersion) == false) || (CFG_IsValidVersion(maxVersion) == false) || (IS_DTLS_VERSION(minVersion) != IS_DTLS_VERSION(maxVersion))) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15781, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Config max version [0x%x] or min version [0x%x] is invalid.", maxVersion, minVersion, 0, 0); return HITLS_CONFIG_INVALID_VERSION; } if ((IS_DTLS_VERSION(maxVersion) && (maxVersion > minVersion))) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15782, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Config max version [0x%x] or min version [0x%x] is invalid.", maxVersion, minVersion, 0, 0); return HITLS_CONFIG_INVALID_VERSION; } if ((IS_DTLS_VERSION(maxVersion) == false) && (maxVersion < minVersion)) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_VERSION); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15783, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Config max version [0x%x] or min version [0x%x] is invalid.", maxVersion, minVersion, 0, 0); return HITLS_CONFIG_INVALID_VERSION; } #ifdef HITLS_TLS_PROTO_TLCP11 if (minVersion == HITLS_VERSION_TLCP_DTLCP11 || maxVersion == HITLS_VERSION_TLCP_DTLCP11) { if (minVersion != maxVersion) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16233, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Config max version [0x%x] or min version [0x%x] is invalid.", maxVersion, minVersion, 0, 0); return HITLS_CONFIG_INVALID_VERSION; } } #endif return HITLS_SUCCESS; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) static int32_t CheckCallbackFunc(const TLS_Config *config) { /* Check the cookie callback. The user must register the cookie callback at the same time or not register the cookie callback */ if ((config->appGenCookieCb != NULL && config->appVerifyCookieCb == NULL) || (config->appGenCookieCb == NULL && config->appVerifyCookieCb != NULL)) { BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_SET); BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15784, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "cannot register only one cookie callback, either appGenCookieCb or appVerifyCookieCb is NULL.", 0, 0, 0, 0); return HITLS_CONFIG_INVALID_SET; } return HITLS_SUCCESS; } #endif int32_t CheckConfig(const TLS_Config *config) { int32_t ret; /** The check of the cipher suite is checked during setting. The algorithm suite needs to be sorted and the memory * overhead increases. Therefore, the algorithm suite is still placed in the Set interface */ if (config->cipherSuitesSize == 0 #ifdef HITLS_TLS_PROTO_TLS13 && config->tls13cipherSuitesSize == 0 #endif ) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16562, BSL_LOG_LEVEL_INFO, BSL_LOG_BINLOG_TYPE_RUN, "cipherSuitesSize is 0", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CONFIG_INVALID_SET); return HITLS_CONFIG_INVALID_SET; } /* The checkpoint format and group are required only when the ecdhe cipher suite is available */ if (IsHaveEccCipherSuite(config)) { ret = CheckPointFormats(config); if (ret != HITLS_SUCCESS) { return ret; } ret = CheckGroup(config); if (ret != HITLS_SUCCESS) { return ret; } } ret = CheckSign(config); if (ret != HITLS_SUCCESS) { return ret; } #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) ret = CheckCallbackFunc(config); #endif return ret; }
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config_check.c
C
unknown
10,747
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_type.h" #include "hitls_crypt_type.h" #include "hitls_config.h" #include "hitls_error.h" #include "tls_config.h" #include "config.h" #include "cipher_suite.h" #include "cert_mgr.h" #ifdef HITLS_TLS_FEATURE_SESSION #include "session_mgr.h" #endif #ifdef HITLS_TLS_FEATURE_SECURITY #include "security.h" #endif #include "config_type.h" #ifdef HITLS_TLS_PROTO_TLCP11 uint16_t g_tlcpCipherSuites[] = { HITLS_ECDHE_SM4_CBC_SM3, HITLS_ECC_SM4_CBC_SM3, HITLS_ECDHE_SM4_GCM_SM3, HITLS_ECC_SM4_GCM_SM3, }; #endif uint16_t g_tls12CipherSuites[] = { HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_CCM, HITLS_ECDHE_ECDSA_WITH_AES_256_CCM, HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, HITLS_DHE_RSA_WITH_AES_128_CCM, HITLS_DHE_RSA_WITH_AES_256_CCM, HITLS_DHE_RSA_WITH_AES_256_CBC_SHA256, HITLS_DHE_DSS_WITH_AES_256_CBC_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, HITLS_DHE_RSA_WITH_AES_128_CBC_SHA256, HITLS_DHE_DSS_WITH_AES_128_CBC_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, HITLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, HITLS_DHE_RSA_WITH_AES_256_CBC_SHA, HITLS_DHE_DSS_WITH_AES_256_CBC_SHA, HITLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, HITLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, HITLS_DHE_RSA_WITH_AES_128_CBC_SHA, HITLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384, HITLS_RSA_PSK_WITH_AES_256_GCM_SHA384, HITLS_DHE_PSK_WITH_AES_256_GCM_SHA384, HITLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_DSS_WITH_AES_128_CBC_SHA, HITLS_RSA_WITH_AES_256_GCM_SHA384, HITLS_PSK_WITH_AES_256_GCM_SHA384, HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256, HITLS_RSA_PSK_WITH_AES_128_GCM_SHA256, HITLS_DHE_PSK_WITH_AES_128_GCM_SHA256, HITLS_RSA_WITH_AES_128_GCM_SHA256, HITLS_PSK_WITH_AES_128_GCM_SHA256, HITLS_PSK_WITH_AES_256_CCM, HITLS_RSA_WITH_AES_256_CBC_SHA256, HITLS_RSA_WITH_AES_128_CBC_SHA256, HITLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256, HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, HITLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, HITLS_RSA_PSK_WITH_AES_256_CBC_SHA384, HITLS_DHE_PSK_WITH_AES_128_CCM, HITLS_DHE_PSK_WITH_AES_256_CCM, HITLS_DHE_PSK_WITH_AES_256_CBC_SHA384, HITLS_RSA_PSK_WITH_AES_256_CBC_SHA, HITLS_DHE_PSK_WITH_AES_256_CBC_SHA, HITLS_RSA_WITH_AES_256_CBC_SHA, HITLS_PSK_WITH_AES_256_CBC_SHA384, HITLS_PSK_WITH_AES_256_CBC_SHA, HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, HITLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, HITLS_RSA_PSK_WITH_AES_128_CBC_SHA256, HITLS_DHE_PSK_WITH_AES_128_CBC_SHA256, HITLS_RSA_PSK_WITH_AES_128_CBC_SHA, HITLS_DHE_PSK_WITH_AES_128_CBC_SHA, HITLS_RSA_WITH_AES_128_CBC_SHA, HITLS_PSK_WITH_AES_128_CBC_SHA256, HITLS_PSK_WITH_AES_128_CBC_SHA, }; int32_t SetDefaultCipherSuite(HITLS_Config *config, const uint16_t *cipherSuites, uint32_t cipherSuiteSize) { BSL_SAL_FREE(config->cipherSuites); config->cipherSuites = BSL_SAL_Dump(cipherSuites, cipherSuiteSize); if (config->cipherSuites == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16563, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } config->cipherSuitesSize = cipherSuiteSize / sizeof(uint16_t); return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 static int32_t SetTLS13DefaultCipherSuites(HITLS_Config *config) { const uint16_t ciphersuites13[] = { HITLS_AES_256_GCM_SHA384, HITLS_CHACHA20_POLY1305_SHA256, HITLS_AES_128_GCM_SHA256, }; BSL_SAL_FREE(config->tls13CipherSuites); config->tls13CipherSuites = BSL_SAL_Dump(ciphersuites13, sizeof(ciphersuites13)); if (config->tls13CipherSuites == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16564, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } config->tls13cipherSuitesSize = sizeof(ciphersuites13) / sizeof(uint16_t); return HITLS_SUCCESS; } #endif static int32_t SetDefaultPointFormats(HITLS_Config *config) { const uint8_t pointFormats[] = {HITLS_POINT_FORMAT_UNCOMPRESSED}; uint32_t size = sizeof(pointFormats); BSL_SAL_FREE(config->pointFormats); config->pointFormats = BSL_SAL_Dump(pointFormats, size); if (config->pointFormats == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16565, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Dump fail", 0, 0, 0, 0); return HITLS_MEMALLOC_FAIL; } config->pointFormatsSize = size / sizeof(uint8_t); return HITLS_SUCCESS; } static void BasicInitConfig(HITLS_Config *config) { config->isSupportExtendMasterSecret = false; config->emptyRecordsNum = HITLS_MAX_EMPTY_RECORDS; #ifdef HITLS_TLS_PROTO_TLS13 config->isMiddleBoxCompat = true; #endif #ifdef HITLS_TLS_FEATURE_MODE config->modeSupport = HITLS_MODE_AUTO_RETRY; #endif #ifdef HITLS_TLS_FEATURE_MAX_SEND_FRAGMENT config->maxSendFragment = HITLS_MAX_SEND_FRAGMENT_DEFAULT; #endif #ifdef HITLS_TLS_FEATURE_REC_INBUFFER_SIZE config->recInbufferSize = 0; #endif #if defined(HITLS_TLS_PROTO_TLS_BASIC) || defined(HITLS_TLS_PROTO_DTLS12) config->allowLegacyRenegotiate = false; #endif #ifdef HITLS_TLS_FEATURE_ETM config->isEncryptThenMac = true; #endif } static void InitConfig(HITLS_Config *config) { BasicInitConfig(config); #ifdef HITLS_TLS_FEATURE_RENEGOTIATION config->allowClientRenegotiate = false; config->isSupportRenegotiation = false; #endif #if defined(HITLS_TLS_FEATURE_RENEGOTIATION) && defined(HITLS_TLS_FEATURE_SESSION) config->isResumptionOnRenego = false; #endif #ifdef HITLS_TLS_SUITE_KX_RSA config->needCheckPmsVersion = false; #endif config->readAhead = 0; #ifdef HITLS_TLS_CONFIG_KEY_USAGE config->needCheckKeyUsage = true; #endif #ifdef HITLS_TLS_CONFIG_MANUAL_DH config->isSupportDhAuto = false; #endif if (config->maxVersion == HITLS_VERSION_TLCP_DTLCP11) { config->isSupportExtendMasterSecret = false; } #ifdef HITLS_TLS_FEATURE_FLIGHT config->isFlightTransmitEnable = true; #endif #if defined(HITLS_TLS_PROTO_DTLS12) && defined(HITLS_BSL_UIO_UDP) config->isSupportDtlsCookieExchange = false; #endif #ifdef HITLS_TLS_FEATURE_CERT_MODE /** Set the certificate verification mode */ config->isSupportClientVerify = false; config->isSupportNoClientCert = true; config->isSupportVerifyNone = false; #endif #ifdef HITLS_TLS_FEATURE_PHA config->isSupportPostHandshakeAuth = false; #endif #if defined(HITLS_TLS_FEATURE_RENEGOTIATION) && defined(HITLS_TLS_FEATURE_CERT_MODE) config->isSupportClientOnceVerify = false; #endif config->isQuietShutdown = false; config->maxCertList = HITLS_MAX_CERT_LIST_DEFAULT; config->isKeepPeerCert = true; #ifdef HITLS_TLS_FEATURE_SESSION_TICKET config->isSupportSessionTicket = true; config->ticketNums = HITLS_TLS13_TICKET_NUM_DEFAULT; #endif #ifdef HITLS_TLS_FEATURE_SECURITY // Default security settings SECURITY_SetDefault(config); #endif } static int32_t DefaultCipherSuitesByVersion(uint16_t version, HITLS_Config *config) { const uint16_t *groups = g_tls12CipherSuites; uint32_t size = sizeof(g_tls12CipherSuites); switch (version) { #ifdef HITLS_TLS_PROTO_TLCP11 case HITLS_VERSION_TLCP_DTLCP11: groups = g_tlcpCipherSuites; size = sizeof(g_tlcpCipherSuites); break; #endif default: break; } return SetDefaultCipherSuite(config, groups, size); } int32_t DefaultConfig(HITLS_Lib_Ctx *libCtx, const char *attrName, uint16_t version, HITLS_Config *config) { // Static settings config->minVersion = version; config->maxVersion = version; config->libCtx = libCtx; config->attrName = attrName; InitConfig(config); int32_t ret = DefaultCipherSuitesByVersion(version, config); if (ret != HITLS_SUCCESS) { goto ERR; } #ifdef HITLS_TLS_PROTO_TLS13 /* Configure the TLS1.3 cipher suite for all TLS versions */ ret = SetTLS13DefaultCipherSuites(config); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16570, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SetCipherSuites fail", 0, 0, 0, 0); goto ERR; } #endif if (ConfigLoadSignatureSchemeInfo(config) != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16571, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SetSignHashAlg fail", 0, 0, 0, 0); goto ERR; } if ((SetDefaultPointFormats(config) != HITLS_SUCCESS) || (ConfigLoadGroupInfo(config) != HITLS_SUCCESS)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16572, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SetPointFormats or SetGroups fail", 0, 0, 0, 0); goto ERR; } if (SAL_CERT_MgrIsEnable()) { config->certMgrCtx = SAL_CERT_MgrCtxProviderNew(libCtx, attrName); if (config->certMgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16573, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sessMgr new fail", 0, 0, 0, 0); goto ERR; } } #ifdef HITLS_TLS_FEATURE_SESSION config->sessMgr = SESSMGR_New(config->libCtx); if (config->sessMgr == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16574, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sessMgr new fail", 0, 0, 0, 0); goto ERR; } #endif return HITLS_SUCCESS; ERR: CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t DefaultTLS13Config(HITLS_Config *config) { // Static settings config->minVersion = HITLS_VERSION_TLS13; config->maxVersion = HITLS_VERSION_TLS13; InitConfig(config); // Dynamic setting. By default, only the cipher suite and point format are set. For details, see the comments in // HITLS_CFG_NewDTLS12Config. if ((SetTLS13DefaultCipherSuites(config) != HITLS_SUCCESS) || (SetDefaultPointFormats(config) != HITLS_SUCCESS) || (ConfigLoadGroupInfo(config) != HITLS_SUCCESS) || (ConfigLoadSignatureSchemeInfo(config) != HITLS_SUCCESS)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16575, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Failed to set the default configuration of tls13", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } config->keyExchMode = TLS13_KE_MODE_PSK_WITH_DHE; if (SAL_CERT_MgrIsEnable()) { config->certMgrCtx = SAL_CERT_MgrCtxProviderNew(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config)); if (config->certMgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16576, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "certMgrCtx new fail", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } } #ifdef HITLS_TLS_FEATURE_SESSION config->sessMgr = SESSMGR_New(config->libCtx); if (config->sessMgr == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16577, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sessMgr new fail", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } #endif return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_ALL static int32_t SetDefaultTlsAllCipherSuites(HITLS_Config *config) { #ifdef HITLS_TLS_PROTO_TLS13 int32_t ret = SetTLS13DefaultCipherSuites(config); if (ret != HITLS_SUCCESS) { return ret; } #endif return SetDefaultCipherSuite(config, g_tls12CipherSuites, sizeof(g_tls12CipherSuites)); } #endif #ifdef HITLS_TLS_PROTO_ALL int32_t DefaultTlsAllConfig(HITLS_Config *config) { // Support full version config->minVersion = HITLS_VERSION_TLS12; config->maxVersion = HITLS_VERSION_TLS13; InitConfig(config); // Dynamic setting if ((SetDefaultTlsAllCipherSuites(config) != HITLS_SUCCESS) || (SetDefaultPointFormats(config) != HITLS_SUCCESS) || (ConfigLoadGroupInfo(config) != HITLS_SUCCESS) || (ConfigLoadSignatureSchemeInfo(config) != HITLS_SUCCESS)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16578, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Failed to set the default configuration of tls_all", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } config->keyExchMode = TLS13_KE_MODE_PSK_WITH_DHE; if (SAL_CERT_MgrIsEnable()) { config->certMgrCtx = SAL_CERT_MgrCtxProviderNew(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config)); if (config->certMgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16579, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "MgrCtx new fail", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } } #ifdef HITLS_TLS_FEATURE_SESSION config->sessMgr = SESSMGR_New(config->libCtx); if (config->sessMgr == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16580, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "sessMgr new fail", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } #endif return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_PROTO_DTLS static int32_t SetDefaultDtlsAllCipherSuites(HITLS_Config *config) { const uint16_t cipherSuites[] = { /* DTLS1.2 */ HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_DHE_DSS_WITH_AES_256_GCM_SHA384, HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384, HITLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, HITLS_DHE_DSS_WITH_AES_128_GCM_SHA256, HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256, /* The DTLS1.0 cipher suite is not supported */ }; return SetDefaultCipherSuite(config, cipherSuites, sizeof(cipherSuites)); } int32_t DefaultDtlsAllConfig(HITLS_Config *config) { // Static settings config->minVersion = HITLS_VERSION_DTLS12; // does not support DTLS 1.0. Therefore, the minimum version number is set to DTLS 1.2. config->maxVersion = HITLS_VERSION_DTLS12; InitConfig(config); // Dynamic setting if ((SetDefaultDtlsAllCipherSuites(config) != HITLS_SUCCESS) || (SetDefaultPointFormats(config) != HITLS_SUCCESS) || (ConfigLoadGroupInfo(config) != HITLS_SUCCESS) || (ConfigLoadSignatureSchemeInfo(config) != HITLS_SUCCESS)) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16581, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "set default config fail", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } if (SAL_CERT_MgrIsEnable()) { config->certMgrCtx = SAL_CERT_MgrCtxProviderNew(LIBCTX_FROM_CONFIG(config), ATTRIBUTE_FROM_CONFIG(config)); if (config->certMgrCtx == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16582, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "MgrCtxNew fail", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } } #ifdef HITLS_TLS_FEATURE_SESSION config->sessMgr = SESSMGR_New(config->libCtx); if (config->sessMgr == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16583, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "SESSMGR_New fail", 0, 0, 0, 0); CFG_CleanConfig(config); return HITLS_MEMALLOC_FAIL; } #endif return HITLS_SUCCESS; } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config_default.c
C
unknown
16,906
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CONFIG_DEFAULT_H #define CONFIG_DEFAULT_H #include <stdint.h> #include "hitls_type.h" #ifdef __cplusplus extern "C" { #endif HITLS_Config *CreateConfig(void); #ifdef HITLS_TLS_PROTO_ALL /* provide default configuration */ int32_t DefaultTlsAllConfig(HITLS_Config *config); #endif #ifdef HITLS_TLS_PROTO_DTLS int32_t DefaultDtlsAllConfig(HITLS_Config *config); #endif int32_t DefaultConfig(HITLS_Lib_Ctx *libCtx, const char *attrName, uint16_t version, HITLS_Config *config); #ifdef HITLS_TLS_PROTO_TLS13 int32_t DefaultTLS13Config(HITLS_Config *config); #endif #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config_default.h
C
unknown
1,150
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stddef.h> #include "hitls_build.h" #include "config_type.h" #include "hitls_crypt_type.h" #include "tls_config.h" #include "hitls_error.h" #include "crypt_algid.h" #include "config.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "securec.h" #include "crypt_eal_provider.h" #include "crypt_params_key.h" #include "crypt_eal_implprovider.h" #include "crypt_eal_pkey.h" #endif static const uint16_t DEFAULT_GROUP_ID[] = { HITLS_HYBRID_X25519_MLKEM768, HITLS_EC_GROUP_CURVE25519, HITLS_EC_GROUP_SECP256R1, HITLS_EC_GROUP_SECP384R1, HITLS_EC_GROUP_SECP521R1, HITLS_EC_GROUP_SM2, HITLS_FF_DHE_2048, HITLS_FF_DHE_3072, HITLS_FF_DHE_4096, HITLS_FF_DHE_6144, HITLS_FF_DHE_8192, }; #ifndef HITLS_TLS_FEATURE_PROVIDER static const TLS_GroupInfo GROUP_INFO[] = { { "x25519", CRYPT_PKEY_PARAID_MAX, CRYPT_PKEY_X25519, 128, // secBits HITLS_EC_GROUP_CURVE25519, // groupId 32, 32, 0, // pubkeyLen=32, sharedkeyLen=32 (256 bits) TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits false, }, #ifdef HITLS_TLS_FEATURE_KEM { "X25519MLKEM768", CRYPT_HYBRID_X25519_MLKEM768, CRYPT_PKEY_HYBRID_KEM, 192, // secBits HITLS_HYBRID_X25519_MLKEM768, // groupId 1184 + 32, 32 + 32, 1088 + 32, // pubkeyLen=1216, sharedkeyLen=64, ciphertextLen=1120 TLS13_VERSION_BIT, // versionBits true, }, { "SecP256r1MLKEM768", CRYPT_HYBRID_ECDH_NISTP256_MLKEM768, CRYPT_PKEY_HYBRID_KEM, 192, // secBits HITLS_HYBRID_ECDH_NISTP256_MLKEM768, // groupId 1184 + 65, 32 + 32, 1088 + 65, // pubkeyLen=1249, sharedkeyLen=64, ciphertextLen=1153 TLS13_VERSION_BIT, // versionBits true, }, { "SecP384r1MLKEM1024", CRYPT_HYBRID_ECDH_NISTP384_MLKEM1024, CRYPT_PKEY_HYBRID_KEM, 256, // secBits HITLS_HYBRID_ECDH_NISTP384_MLKEM1024, // groupId 1568 + 97, 32 + 48, 1568 + 97, // pubkeyLen=1665, sharedkeyLen=80, ciphertextLen=1665 TLS13_VERSION_BIT, // versionBits true, }, #endif /* HITLS_TLS_FEATURE_KEM */ { "secp256r1", CRYPT_ECC_NISTP256, // CRYPT_ECC_NISTP256 CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH 128, // secBits HITLS_EC_GROUP_SECP256R1, // groupId 65, 32, 0, // pubkeyLen=65, sharedkeyLen=32 (256 bits) TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits false, }, { "secp384r1", CRYPT_ECC_NISTP384, // CRYPT_ECC_NISTP384 CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH 192, // secBits HITLS_EC_GROUP_SECP384R1, // groupId 97, 48, 0, // pubkeyLen=97, sharedkeyLen=48 (384 bits) TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits false, }, { "secp521r1", CRYPT_ECC_NISTP521, // CRYPT_ECC_NISTP521 CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH 256, // secBits HITLS_EC_GROUP_SECP521R1, // groupId 133, 66, 0, // pubkeyLen=133, sharedkeyLen=66 (521 bits) TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits false, }, { "brainpoolP256r1", CRYPT_ECC_BRAINPOOLP256R1, // CRYPT_ECC_BRAINPOOLP256R1 CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH 128, // secBits HITLS_EC_GROUP_BRAINPOOLP256R1, // groupId 65, 32, 0, // pubkeyLen=65, sharedkeyLen=32 (256 bits) TLS10_VERSION_BIT | TLS11_VERSION_BIT| TLS12_VERSION_BIT | DTLS_VERSION_MASK, // versionBits false, }, { "brainpoolP384r1", CRYPT_ECC_BRAINPOOLP384R1, // CRYPT_ECC_BRAINPOOLP384R1 CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH 192, // secBits HITLS_EC_GROUP_BRAINPOOLP384R1, // groupId 97, 48, 0, // pubkeyLen=97, sharedkeyLen=48 (384 bits) TLS10_VERSION_BIT| TLS11_VERSION_BIT|TLS12_VERSION_BIT | DTLS_VERSION_MASK, // versionBits false, }, { "brainpoolP512r1", CRYPT_ECC_BRAINPOOLP512R1, // CRYPT_ECC_BRAINPOOLP512R1 CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH 256, // secBits HITLS_EC_GROUP_BRAINPOOLP512R1, // groupId 129, 64, 0, // pubkeyLen=129, sharedkeyLen=64 (512 bits) TLS10_VERSION_BIT| TLS11_VERSION_BIT|TLS12_VERSION_BIT | DTLS_VERSION_MASK, // versionBits false, }, { "sm2", CRYPT_PKEY_PARAID_MAX, // CRYPT_PKEY_PARAID_MAX CRYPT_PKEY_SM2, // CRYPT_PKEY_SM2 128, // secBits HITLS_EC_GROUP_SM2, // groupId 65, 32, 0, // pubkeyLen=65, sharedkeyLen=32 (256 bits) TLCP11_VERSION_BIT | DTLCP11_VERSION_BIT, // versionBits false, }, { "ffdhe8192", CRYPT_DH_RFC7919_8192, // CRYPT_DH_8192 CRYPT_PKEY_DH, // CRYPT_PKEY_DH 192, // secBits HITLS_FF_DHE_8192, // groupId 1024, 1024, 0, // pubkeyLen=1024, sharedkeyLen=1024 (8192 bits) TLS13_VERSION_BIT, // versionBits false, }, { "ffdhe6144", CRYPT_DH_RFC7919_6144, // CRYPT_DH_6144 CRYPT_PKEY_DH, // CRYPT_PKEY_DH 128, // secBits HITLS_FF_DHE_6144, // groupId 768, 768, 0, // pubkeyLen=768, sharedkeyLen=768 (6144 bits) TLS13_VERSION_BIT, // versionBits false, }, { "ffdhe4096", CRYPT_DH_RFC7919_4096, // CRYPT_DH_4096 CRYPT_PKEY_DH, // CRYPT_PKEY_DH 128, // secBits HITLS_FF_DHE_4096, // groupId 512, 512, 0, // pubkeyLen=512, sharedkeyLen=512 (4096 bits) TLS13_VERSION_BIT, // versionBits false, }, { "ffdhe3072", CRYPT_DH_RFC7919_3072, // Fixed constant name CRYPT_PKEY_DH, 128, HITLS_FF_DHE_3072, 384, 384, 0, // pubkeyLen=384, sharedkeyLen=384 (3072 bits) TLS13_VERSION_BIT, false, }, { "ffdhe2048", CRYPT_DH_RFC7919_2048, // CRYPT_DH_2048 CRYPT_PKEY_DH, // CRYPT_PKEY_DH 112, // secBits HITLS_FF_DHE_2048, // groupId 256, 256, 0, // pubkeyLen=256, sharedkeyLen=256 (2048 bits) TLS13_VERSION_BIT, // versionBits false, } }; int32_t ConfigLoadGroupInfo(HITLS_Config *config) { if (config == NULL) { return HITLS_INVALID_INPUT; } return HITLS_CFG_SetGroups(config, DEFAULT_GROUP_ID, sizeof(DEFAULT_GROUP_ID) / sizeof(DEFAULT_GROUP_ID[0])); } const TLS_GroupInfo *ConfigGetGroupInfo(const HITLS_Config *config, uint16_t groupId) { (void)config; for (uint32_t i = 0; i < sizeof(GROUP_INFO) / sizeof(TLS_GroupInfo); i++) { if (GROUP_INFO[i].groupId == groupId) { return &GROUP_INFO[i]; } } return NULL; } const TLS_GroupInfo *ConfigGetGroupInfoList(const HITLS_Config *config, uint32_t *size) { (void)config; *size = sizeof(GROUP_INFO) / sizeof(GROUP_INFO[0]); return &GROUP_INFO[0]; } #else static int32_t ProviderAddGroupInfo(const BSL_Param *params, void *args) { if (params == NULL || args == NULL) { return HITLS_INVALID_INPUT; } TLS_CapabilityData *data = (TLS_CapabilityData *)args; TLS_Config *config = data->config; TLS_GroupInfo *group = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; BSL_Param *param = NULL; int32_t ret = HITLS_CONFIG_ERR_LOAD_GROUP_INFO; if (config->groupInfolen == config->groupInfoSize) { void *ptr = BSL_SAL_Realloc(config->groupInfo, (config->groupInfoSize + TLS_CAPABILITY_LIST_MALLOC_SIZE) * sizeof(TLS_GroupInfo), config->groupInfoSize * sizeof(TLS_GroupInfo)); if (ptr == NULL) { return HITLS_MEMALLOC_FAIL; } config->groupInfo = ptr; (void)memset_s(config->groupInfo + config->groupInfoSize, TLS_CAPABILITY_LIST_MALLOC_SIZE * sizeof(TLS_GroupInfo), 0, TLS_CAPABILITY_LIST_MALLOC_SIZE * sizeof(TLS_GroupInfo)); config->groupInfoSize += TLS_CAPABILITY_LIST_MALLOC_SIZE; } group = config->groupInfo + config->groupInfolen; PROCESS_STRING_PARAM(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_IANA_GROUP_NAME, name); PROCESS_PARAM_UINT16(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_IANA_GROUP_ID, groupId); PROCESS_PARAM_INT32(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_PARA_ID, paraId); PROCESS_PARAM_INT32(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_ALG_ID, algId); PROCESS_PARAM_INT32(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_SEC_BITS, secBits); PROCESS_PARAM_UINT32(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_VERSION_BITS, versionBits); PROCESS_PARAM_BOOL(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_IS_KEM, isKem); PROCESS_PARAM_INT32(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_PUBKEY_LEN, pubkeyLen); PROCESS_PARAM_INT32(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_SHAREDKEY_LEN, sharedkeyLen); PROCESS_PARAM_INT32(param, group, params, CRYPT_PARAM_CAP_TLS_GROUP_CIPHERTEXT_LEN, ciphertextLen); ret = HITLS_SUCCESS; pkey = CRYPT_EAL_ProviderPkeyNewCtx(LIBCTX_FROM_CONFIG(config), group->algId, group->isKem ? CRYPT_EAL_PKEY_KEM_OPERATE : CRYPT_EAL_PKEY_EXCH_OPERATE, ATTRIBUTE_FROM_CONFIG(config)); if (pkey != NULL) { config->groupInfolen++; CRYPT_EAL_PkeyFreeCtx(pkey); group = NULL; } ERR: if (group != NULL) { BSL_SAL_Free(group->name); (void)memset_s(group, sizeof(TLS_GroupInfo), 0, sizeof(TLS_GroupInfo)); } return ret; } static int32_t ProviderLoadGroupInfo(CRYPT_EAL_ProvMgrCtx *ctx, void *args) { if (ctx == NULL || args == NULL) { return HITLS_INVALID_INPUT; } TLS_CapabilityData data = { .config = (TLS_Config *)args, .provMgrCtx = ctx, }; return CRYPT_EAL_ProviderGetCaps(ctx, CRYPT_EAL_GET_GROUP_CAP, ProviderAddGroupInfo, &data); } int32_t ConfigLoadGroupInfo(HITLS_Config *config) { HITLS_Lib_Ctx *libCtx = LIBCTX_FROM_CONFIG(config); int32_t ret = CRYPT_EAL_ProviderProcessAll(libCtx, ProviderLoadGroupInfo, config); if (ret != HITLS_SUCCESS) { return ret; } return HITLS_CFG_SetGroups(config, DEFAULT_GROUP_ID, sizeof(DEFAULT_GROUP_ID) / sizeof(DEFAULT_GROUP_ID[0])); } const TLS_GroupInfo *ConfigGetGroupInfo(const HITLS_Config *config, uint16_t groupId) { for (uint32_t i = 0; i < config->groupInfolen; i++) { if (config->groupInfo[i].groupId == groupId) { return &config->groupInfo[i]; } } return NULL; } const TLS_GroupInfo *ConfigGetGroupInfoList(const HITLS_Config *config, uint32_t *size) { *size = config->groupInfolen; return config->groupInfo; } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config_group.c
C
unknown
11,592
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stddef.h> #include "hitls_build.h" #include "config_type.h" #include "hitls_cert_type.h" #include "tls_config.h" #include "crypt_algid.h" #include "hitls_error.h" #include "cipher_suite.h" #include "config.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "securec.h" #include "crypt_eal_provider.h" #include "crypt_params_key.h" #include "crypt_eal_implprovider.h" #include "crypt_eal_pkey.h" #endif static const uint16_t DEFAULT_SIGSCHEME_ID[] = { CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512, CERT_SIG_SCHEME_ED25519, CERT_SIG_SCHEME_SM2_SM3, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384, CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512, CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256, CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384, CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512, CERT_SIG_SCHEME_RSA_PKCS1_SHA256, CERT_SIG_SCHEME_RSA_PKCS1_SHA384, CERT_SIG_SCHEME_RSA_PKCS1_SHA512, CERT_SIG_SCHEME_ECDSA_SHA224, CERT_SIG_SCHEME_ECDSA_SHA1, CERT_SIG_SCHEME_RSA_PKCS1_SHA224, CERT_SIG_SCHEME_RSA_PKCS1_SHA1, CERT_SIG_SCHEME_DSA_SHA224, CERT_SIG_SCHEME_DSA_SHA256, CERT_SIG_SCHEME_DSA_SHA384, CERT_SIG_SCHEME_DSA_SHA512, CERT_SIG_SCHEME_DSA_SHA1, }; static int32_t UpdateSignAlgorithmsArray(TLS_Config *config) { if (config == NULL) { return HITLS_INVALID_INPUT; } uint16_t *tempItems = BSL_SAL_Calloc(sizeof(DEFAULT_SIGSCHEME_ID), sizeof(uint8_t)); if (tempItems == NULL) { return HITLS_MEMALLOC_FAIL; } uint32_t size = 0; for (uint32_t i = 0; i < sizeof(DEFAULT_SIGSCHEME_ID) / sizeof(DEFAULT_SIGSCHEME_ID[0]); i++) { const TLS_SigSchemeInfo *info = ConfigGetSignatureSchemeInfo(config, DEFAULT_SIGSCHEME_ID[i]); if (info == NULL || (config->version & info->chainVersionBits) == 0) { continue; } tempItems[size] = DEFAULT_SIGSCHEME_ID[i]; size++; } if (size == 0) { BSL_SAL_Free(tempItems); return HITLS_INVALID_INPUT; } BSL_SAL_FREE(config->signAlgorithms); config->signAlgorithms = tempItems; config->signAlgorithmsSize = size; return HITLS_SUCCESS; } #ifndef HITLS_TLS_FEATURE_PROVIDER static const TLS_SigSchemeInfo SIGNATURE_SCHEME_INFO[] = { { "ecdsa_secp521r1_sha512", CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512, TLS_CERT_KEY_TYPE_ECDSA, CRYPT_ECC_NISTP521, BSL_CID_ECDSAWITHSHA512, HITLS_SIGN_ECDSA, HITLS_HASH_SHA_512, 256, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "ecdsa_secp384r1_sha384", CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384, TLS_CERT_KEY_TYPE_ECDSA, CRYPT_ECC_NISTP384, BSL_CID_ECDSAWITHSHA384, HITLS_SIGN_ECDSA, HITLS_HASH_SHA_384, 192, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "ed25519", CERT_SIG_SCHEME_ED25519, TLS_CERT_KEY_TYPE_ED25519, CRYPT_PKEY_PARAID_MAX, BSL_CID_ED25519, HITLS_SIGN_ED25519, HITLS_HASH_SHA_512, 128, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "ecdsa_secp256r1_sha256", CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256, TLS_CERT_KEY_TYPE_ECDSA, CRYPT_ECC_NISTP256, BSL_CID_ECDSAWITHSHA256, HITLS_SIGN_ECDSA, HITLS_HASH_SHA_256, 128, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "sm2_sm3", CERT_SIG_SCHEME_SM2_SM3, TLS_CERT_KEY_TYPE_SM2, CRYPT_PKEY_PARAID_MAX, BSL_CID_SM2DSAWITHSM3, HITLS_SIGN_SM2, HITLS_HASH_SM3, 128, TLCP11_VERSION_BIT | DTLCP11_VERSION_BIT, TLCP11_VERSION_BIT | DTLCP11_VERSION_BIT, }, { "rsa_pss_pss_sha512", CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512, TLS_CERT_KEY_TYPE_RSA_PSS, CRYPT_PKEY_PARAID_MAX, BSL_CID_RSASSAPSS, HITLS_SIGN_RSA_PSS, HITLS_HASH_SHA_512, 256, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "rsa_pss_pss_sha384", CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384, TLS_CERT_KEY_TYPE_RSA_PSS, CRYPT_PKEY_PARAID_MAX, BSL_CID_RSASSAPSS, HITLS_SIGN_RSA_PSS, HITLS_HASH_SHA_384, 192, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "rsa_pss_pss_sha256", CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256, TLS_CERT_KEY_TYPE_RSA_PSS, CRYPT_PKEY_PARAID_MAX, BSL_CID_RSASSAPSS, HITLS_SIGN_RSA_PSS, HITLS_HASH_SHA_256, 128, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "rsa_pss_rsae_sha512", CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_RSASSAPSS, HITLS_SIGN_RSA_PSS, HITLS_HASH_SHA_512, 256, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "rsa_pss_rsae_sha384", CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_RSASSAPSS, HITLS_SIGN_RSA_PSS, HITLS_HASH_SHA_384, 192, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "rsa_pss_rsae_sha256", CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_RSASSAPSS, HITLS_SIGN_RSA_PSS, HITLS_HASH_SHA_256, 128, TLS_VERSION_MASK | DTLS_VERSION_MASK, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "rsa_pkcs1_sha512", CERT_SIG_SCHEME_RSA_PKCS1_SHA512, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_SHA512WITHRSAENCRYPTION, HITLS_SIGN_RSA_PKCS1_V15, HITLS_HASH_SHA_512, 256, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "dsa_sha512", CERT_SIG_SCHEME_DSA_SHA512, TLS_CERT_KEY_TYPE_DSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_DSAWITHSHA512, HITLS_SIGN_DSA, HITLS_HASH_SHA_512, 256, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "rsa_pkcs1_sha384", CERT_SIG_SCHEME_RSA_PKCS1_SHA384, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_SHA384WITHRSAENCRYPTION, HITLS_SIGN_RSA_PKCS1_V15, HITLS_HASH_SHA_384, 192, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "dsa_sha384", CERT_SIG_SCHEME_DSA_SHA384, TLS_CERT_KEY_TYPE_DSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_DSAWITHSHA384, HITLS_SIGN_DSA, HITLS_HASH_SHA_384, 192, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "rsa_pkcs1_sha256", CERT_SIG_SCHEME_RSA_PKCS1_SHA256, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_SHA256WITHRSAENCRYPTION, HITLS_SIGN_RSA_PKCS1_V15, HITLS_HASH_SHA_256, 128, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS_VERSION_MASK | DTLS_VERSION_MASK, }, { "dsa_sha256", CERT_SIG_SCHEME_DSA_SHA256, TLS_CERT_KEY_TYPE_DSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_DSAWITHSHA256, HITLS_SIGN_DSA, HITLS_HASH_SHA_256, 128, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "ecdsa_sha224", CERT_SIG_SCHEME_ECDSA_SHA224, TLS_CERT_KEY_TYPE_ECDSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_ECDSAWITHSHA224, HITLS_SIGN_ECDSA, HITLS_HASH_SHA_224, 112, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "rsa_pkcs1_sha224", CERT_SIG_SCHEME_RSA_PKCS1_SHA224, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_SHA224WITHRSAENCRYPTION, HITLS_SIGN_RSA_PKCS1_V15, HITLS_HASH_SHA_224, 112, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "dsa_sha224", CERT_SIG_SCHEME_DSA_SHA224, TLS_CERT_KEY_TYPE_DSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_DSAWITHSHA224, HITLS_SIGN_DSA, HITLS_HASH_SHA_224, 112, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "ecdsa_sha1", CERT_SIG_SCHEME_ECDSA_SHA1, TLS_CERT_KEY_TYPE_ECDSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_ECDSAWITHSHA1, HITLS_SIGN_ECDSA, HITLS_HASH_SHA1, -1, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "rsa_pkcs1_sha1", CERT_SIG_SCHEME_RSA_PKCS1_SHA1, TLS_CERT_KEY_TYPE_RSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_SHA1WITHRSA, HITLS_SIGN_RSA_PKCS1_V15, HITLS_HASH_SHA1, -1, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, { "dsa_sha1", CERT_SIG_SCHEME_DSA_SHA1, TLS_CERT_KEY_TYPE_DSA, CRYPT_PKEY_PARAID_MAX, BSL_CID_DSAWITHSHA1, HITLS_SIGN_DSA, HITLS_HASH_SHA1, -1, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, TLS12_VERSION_BIT | DTLS12_VERSION_BIT, }, }; int32_t ConfigLoadSignatureSchemeInfo(HITLS_Config *config) { return UpdateSignAlgorithmsArray(config); } const TLS_SigSchemeInfo *ConfigGetSignatureSchemeInfo(const HITLS_Config *config, uint16_t signatureScheme) { (void)config; for (uint32_t i = 0; i < sizeof(SIGNATURE_SCHEME_INFO) / sizeof(TLS_SigSchemeInfo); i++) { if (SIGNATURE_SCHEME_INFO[i].signatureScheme == signatureScheme) { return &SIGNATURE_SCHEME_INFO[i]; } } return NULL; } const TLS_SigSchemeInfo *ConfigGetSignatureSchemeInfoList(const HITLS_Config *config, uint32_t *size) { (void)config; *size = sizeof(SIGNATURE_SCHEME_INFO) / sizeof(SIGNATURE_SCHEME_INFO[0]); return SIGNATURE_SCHEME_INFO; } #else // HITLS_TLS_FEATURE_PROVIDER static int32_t PrepareSignSchemeStorage(TLS_Config *config, TLS_SigSchemeInfo **scheme) { if (config->sigSchemeInfolen == config->sigSchemeInfoSize) { void *ptr = BSL_SAL_Realloc(config->sigSchemeInfo, (config->sigSchemeInfoSize + TLS_CAPABILITY_LIST_MALLOC_SIZE) * sizeof(TLS_SigSchemeInfo), config->sigSchemeInfoSize * sizeof(TLS_SigSchemeInfo)); if (ptr == NULL) { return HITLS_MEMALLOC_FAIL; } config->sigSchemeInfo = ptr; (void)memset_s(config->sigSchemeInfo + config->sigSchemeInfoSize, TLS_CAPABILITY_LIST_MALLOC_SIZE * sizeof(TLS_SigSchemeInfo), 0, TLS_CAPABILITY_LIST_MALLOC_SIZE * sizeof(TLS_SigSchemeInfo)); config->sigSchemeInfoSize += TLS_CAPABILITY_LIST_MALLOC_SIZE; } *scheme = config->sigSchemeInfo + config->sigSchemeInfolen; return HITLS_SUCCESS; } typedef struct { BslOidString oidStr; const char *oidName; } BslOidInfo; static int32_t ProcessOids(TLS_SigSchemeInfo *scheme, BslOidInfo *keyTypeOidInfo, BslOidInfo *paraOidInfo, BslOidInfo *signHashAlgOidInfo, BslOidInfo *hashOidInfo) { int32_t ret = HITLS_SUCCESS; if (keyTypeOidInfo != NULL && keyTypeOidInfo->oidStr.octs != NULL) { ret = BSL_OBJ_Create(keyTypeOidInfo->oidStr.octs, keyTypeOidInfo->oidStr.octetLen, keyTypeOidInfo->oidName, scheme->keyType); if (ret != HITLS_SUCCESS) { return ret; } } if (paraOidInfo != NULL && paraOidInfo->oidStr.octs != NULL) { ret = BSL_OBJ_Create(paraOidInfo->oidStr.octs, paraOidInfo->oidStr.octetLen, paraOidInfo->oidName, scheme->paraId); if (ret != HITLS_SUCCESS) { return ret; } } if (hashOidInfo != NULL && hashOidInfo->oidStr.octs != NULL) { ret = BSL_OBJ_Create(hashOidInfo->oidStr.octs, hashOidInfo->oidStr.octetLen, hashOidInfo->oidName, scheme->hashAlgId); if (ret != HITLS_SUCCESS) { return ret; } } if (signHashAlgOidInfo != NULL && signHashAlgOidInfo->oidStr.octs != NULL) { ret = BSL_OBJ_Create(signHashAlgOidInfo->oidStr.octs, signHashAlgOidInfo->oidStr.octetLen, signHashAlgOidInfo->oidName, scheme->signHashAlgId); if (ret != HITLS_SUCCESS) { return ret; } } return BSL_OBJ_CreateSignId(scheme->signHashAlgId, scheme->signAlgId, scheme->hashAlgId); } static int32_t ProviderAddSignatureSchemeInfo(const BSL_Param *params, void *args) { if (params == NULL || args == NULL) { return HITLS_INVALID_INPUT; } TLS_CapabilityData *data = (TLS_CapabilityData *)args; TLS_Config *config = data->config; TLS_SigSchemeInfo *scheme = NULL; CRYPT_EAL_PkeyCtx *pkey = NULL; BSL_Param *param = NULL; const char *keyTypeOid = NULL, *keyTypeName = NULL, *paraOid = NULL, *paraName = NULL; const char *signHashAlgOid = NULL, *signHashAlgName = NULL, *hashOid = NULL, *hashName = NULL; uint32_t keyTypeOidLen = 0, paraOidLen = 0, signHashAlgOidLen = 0, hashOidLen = 0; int32_t ret = PrepareSignSchemeStorage(config, &scheme); if (ret != HITLS_SUCCESS) { return ret; } ret = HITLS_CONFIG_ERR_LOAD_SIGN_SCHEME_INFO; PROCESS_STRING_PARAM(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_IANA_SIGN_NAME, name); PROCESS_PARAM_UINT16(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_IANA_SIGN_ID, signatureScheme); PROCESS_PARAM_INT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_KEY_TYPE, keyType); PROCESS_PARAM_INT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_PARA_ID, paraId); PROCESS_PARAM_INT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGNWITHMD_ID, signHashAlgId); PROCESS_PARAM_INT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGN_ID, signAlgId); PROCESS_PARAM_INT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_MD_ID, hashAlgId); PROCESS_PARAM_INT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_SEC_BITS, secBits); PROCESS_PARAM_UINT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_CHAIN_VERSION_BITS, chainVersionBits); PROCESS_PARAM_UINT32(param, scheme, params, CRYPT_PARAM_CAP_TLS_SIGNALG_CERT_VERSION_BITS, certVersionBits); PROCESS_OPTIONAL_STRING_PARAM(param, params, CRYPT_PARAM_CAP_TLS_SIGNALG_KEY_TYPE_OID, keyTypeOid, keyTypeOidLen, CRYPT_PARAM_CAP_TLS_SIGNALG_KEY_TYPE_NAME, keyTypeName); PROCESS_OPTIONAL_STRING_PARAM(param, params, CRYPT_PARAM_CAP_TLS_SIGNALG_PARA_OID, paraOid, paraOidLen, CRYPT_PARAM_CAP_TLS_SIGNALG_PARA_NAME, paraName); PROCESS_OPTIONAL_STRING_PARAM(param, params, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGNWITHMD_OID, signHashAlgOid, signHashAlgOidLen, CRYPT_PARAM_CAP_TLS_SIGNALG_SIGNWITHMD_NAME, signHashAlgName); PROCESS_OPTIONAL_STRING_PARAM(param, params, CRYPT_PARAM_CAP_TLS_SIGNALG_MD_OID, hashOid, hashOidLen, CRYPT_PARAM_CAP_TLS_SIGNALG_MD_NAME, hashName); if (scheme->keyType == TLS_CERT_KEY_TYPE_RSA_PSS) { pkey = CRYPT_EAL_ProviderPkeyNewCtx(LIBCTX_FROM_CONFIG(config), TLS_CERT_KEY_TYPE_RSA, CRYPT_EAL_PKEY_SIGN_OPERATE, ATTRIBUTE_FROM_CONFIG(config)); } else { pkey = CRYPT_EAL_ProviderPkeyNewCtx(LIBCTX_FROM_CONFIG(config), scheme->keyType, CRYPT_EAL_PKEY_SIGN_OPERATE, ATTRIBUTE_FROM_CONFIG(config)); } if (pkey == NULL) { goto ERR; } BslOidInfo keyTypeOidInfo = { { keyTypeOidLen, (char *)(uintptr_t)keyTypeOid, 0 }, keyTypeName }; BslOidInfo paraOidInfo = { { paraOidLen, (char *)(uintptr_t)paraOid, 0 }, paraName }; BslOidInfo signHashAlgOidInfo = { { signHashAlgOidLen, (char *)(uintptr_t)signHashAlgOid, 0 }, signHashAlgName }; BslOidInfo hashOidInfo = { { hashOidLen, (char *)(uintptr_t)hashOid, 0 }, hashName }; ret = ProcessOids(scheme, &keyTypeOidInfo, &paraOidInfo, &signHashAlgOidInfo, &hashOidInfo); if (ret != HITLS_SUCCESS) { goto ERR; } config->sigSchemeInfolen++; CRYPT_EAL_PkeyFreeCtx(pkey); return HITLS_SUCCESS; ERR: if (pkey != NULL) { CRYPT_EAL_PkeyFreeCtx(pkey); } if (scheme != NULL) { BSL_SAL_Free(scheme->name); (void)memset_s(scheme, sizeof(TLS_SigSchemeInfo), 0, sizeof(TLS_SigSchemeInfo)); } return ret != HITLS_SUCCESS ? ret : HITLS_CONFIG_ERR_LOAD_SIGN_SCHEME_INFO; } static int32_t ProviderLoadSignSchemeInfo(CRYPT_EAL_ProvMgrCtx *ctx, void *args) { if (ctx == NULL || args == NULL) { return HITLS_INVALID_INPUT; } TLS_CapabilityData data = { .config = (TLS_Config *)args, .provMgrCtx = ctx, }; return CRYPT_EAL_ProviderGetCaps(ctx, CRYPT_EAL_GET_SIGALG_CAP, ProviderAddSignatureSchemeInfo, &data); } int32_t ConfigLoadSignatureSchemeInfo(HITLS_Config *config) { HITLS_Lib_Ctx *libCtx = LIBCTX_FROM_CONFIG(config); int32_t ret = CRYPT_EAL_ProviderProcessAll(libCtx, ProviderLoadSignSchemeInfo, config); if (ret != HITLS_SUCCESS) { return ret; } return UpdateSignAlgorithmsArray(config); } const TLS_SigSchemeInfo *ConfigGetSignatureSchemeInfo(const HITLS_Config *config, uint16_t signatureScheme) { for (uint32_t i = 0; i < config->sigSchemeInfolen; i++) { if (config->sigSchemeInfo[i].signatureScheme == signatureScheme) { return &config->sigSchemeInfo[i]; } } return NULL; } const TLS_SigSchemeInfo *ConfigGetSignatureSchemeInfoList(const HITLS_Config *config, uint32_t *size) { *size = config->sigSchemeInfolen; return config->sigSchemeInfo; } #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config_sign.c
C
unknown
19,071
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_TLS_PROTO_TLS13 #include "securec.h" #include "tls.h" #include "bsl_err_internal.h" #include "hitls_error.h" #include "config_default.h" #ifdef HITLS_TLS_FEATURE_PSK #include "hitls_psk.h" #endif HITLS_Config *HITLS_CFG_NewTLS13Config(void) { return HITLS_CFG_ProviderNewTLS13Config(NULL, NULL); } HITLS_Config *HITLS_CFG_ProviderNewTLS13Config(HITLS_Lib_Ctx *libCtx, const char *attrName) { HITLS_Config *newConfig = CreateConfig(); if (newConfig == NULL) { return NULL; } newConfig->version |= TLS13_VERSION_BIT; // Enable TLS1.3 newConfig->libCtx = libCtx; newConfig->attrName = attrName; if (DefaultTLS13Config(newConfig) != HITLS_SUCCESS) { BSL_SAL_FREE(newConfig); return NULL; } newConfig->originVersionMask = newConfig->version; return newConfig; } int32_t HITLS_CFG_ClearTLS13CipherSuites(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } BSL_SAL_FREE(config->tls13CipherSuites); config->tls13cipherSuitesSize = 0; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetKeyExchMode(HITLS_Config *config, uint32_t mode) { if (config == NULL) { return HITLS_NULL_INPUT; } if (((mode & TLS13_KE_MODE_PSK_ONLY) == TLS13_KE_MODE_PSK_ONLY) || ((mode & TLS13_KE_MODE_PSK_WITH_DHE) == TLS13_KE_MODE_PSK_WITH_DHE)) { config->keyExchMode = (mode & (TLS13_KE_MODE_PSK_ONLY | TLS13_KE_MODE_PSK_WITH_DHE)); return HITLS_SUCCESS; } return HITLS_CONFIG_INVALID_SET; } uint32_t HITLS_CFG_GetKeyExchMode(HITLS_Config *config) { if (config == NULL) { return HITLS_NULL_INPUT; } return config->keyExchMode; } #ifdef HITLS_TLS_FEATURE_PSK int32_t HITLS_CFG_SetPskFindSessionCallback(HITLS_Config *config, HITLS_PskFindSessionCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } config->pskFindSessionCb = callback; return HITLS_SUCCESS; } int32_t HITLS_CFG_SetPskUseSessionCallback(HITLS_Config *config, HITLS_PskUseSessionCb callback) { if (config == NULL) { return HITLS_NULL_INPUT; } config->pskUseSessionCb = callback; return HITLS_SUCCESS; } #endif #ifdef HITLS_TLS_FEATURE_PHA int32_t HITLS_CFG_SetPostHandshakeAuthSupport(HITLS_Config *config, bool support) { if (config == NULL) { return HITLS_NULL_INPUT; } config->isSupportPostHandshakeAuth = support; return HITLS_SUCCESS; } int32_t HITLS_CFG_GetPostHandshakeAuthSupport(HITLS_Config *config, uint8_t *isSupport) { if (config == NULL || isSupport == NULL) { return HITLS_NULL_INPUT; } *isSupport = (uint8_t)config->isSupportPostHandshakeAuth; return HITLS_SUCCESS; } #endif #endif /* HITLS_TLS_PROTO_TLS13 */
2302_82127028/openHiTLS-examples_5062_4009
tls/config/src/config_tls13.c
C
unknown
3,342
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 <stddef.h> #include "securec.h" #include "tls_binlog_id.h" #include "bsl_log_internal.h" #include "bsl_log.h" #include "bsl_err_internal.h" #include "bsl_bytes.h" #include "bsl_sal.h" #include "hitls_error.h" #include "hitls_crypt_reg.h" #include "crypt.h" #include "config_type.h" #include "crypt_algid.h" #ifdef HITLS_TLS_FEATURE_PROVIDER #include "hitls_crypt.h" #endif #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_BaseMethod g_cryptBaseMethod = {0}; HITLS_CRYPT_EcdhMethod g_cryptEcdhMethod = {0}; HITLS_CRYPT_DhMethod g_cryptDhMethod = {0}; #endif #ifdef HITLS_TLS_PROTO_TLS13 #define TLS13_MAX_LABEL_LEN 255 #define TLS13_MAX_CTX_LEN 255 #define TLS13_HKDF_LABEL_LEN(labelLen, ctxLen) \ (sizeof(uint16_t) + sizeof(uint8_t) + (labelLen) + sizeof(uint8_t) + (ctxLen)) #define TLS13_MAX_HKDF_LABEL_LEN TLS13_HKDF_LABEL_LEN(TLS13_MAX_LABEL_LEN, TLS13_MAX_CTX_LEN) #ifndef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_KdfMethod g_cryptKdfMethod = {0}; #endif /* HITLS_TLS_FEATURE_PROVIDER */ typedef struct { uint16_t length; /* Length of the derived key */ uint8_t labelLen; /* Label length */ uint8_t ctxLen; /* Length of the context information */ const uint8_t *label; /* Label */ const uint8_t *ctx; /* Context information */ } HkdfLabel; #endif const char *g_cryptCallBackStr[] = { [HITLS_CRYPT_CALLBACK_RAND_BYTES] = "random bytes", [HITLS_CRYPT_CALLBACK_HMAC_SIZE] = "hmac size", [HITLS_CRYPT_CALLBACK_HMAC_INIT] = "hmac init", [HITLS_CRYPT_CALLBACK_HMAC_FREE] = "hmac free", [HITLS_CRYPT_CALLBACK_HMAC_UPDATE] = "hmac update", [HITLS_CRYPT_CALLBACK_HMAC_FINAL] = "hmac final", [HITLS_CRYPT_CALLBACK_HMAC] = "hmac calc", [HITLS_CRYPT_CALLBACK_DIGEST_SIZE] = "digest size", [HITLS_CRYPT_CALLBACK_DIGEST_INIT] = "digest init", [HITLS_CRYPT_CALLBACK_DIGEST_COPY] = "digest copy", [HITLS_CRYPT_CALLBACK_DIGEST_FREE] = "digest free", [HITLS_CRYPT_CALLBACK_DIGEST_UPDATE] = "digest update", [HITLS_CRYPT_CALLBACK_DIGEST_FINAL] = "digest final", [HITLS_CRYPT_CALLBACK_DIGEST] = "digest calc", [HITLS_CRYPT_CALLBACK_ENCRYPT] = "encrypt", [HITLS_CRYPT_CALLBACK_DECRYPT] = "decrpt", [HITLS_CRYPT_CALLBACK_GENERATE_ECDH_KEY_PAIR] = "generate ecdh key", [HITLS_CRYPT_CALLBACK_FREE_ECDH_KEY] = "free ecdh key", [HITLS_CRYPT_CALLBACK_GET_ECDH_ENCODED_PUBKEY] = "get ecdh public key", [HITLS_CRYPT_CALLBACK_CALC_ECDH_SHARED_SECRET] = "calculate ecdh shared secret", [HITLS_CRYPT_CALLBACK_SM2_CALC_ECDH_SHARED_SECRET] = "calculate sm2 ecdh shared secret", [HITLS_CRYPT_CALLBACK_GENERATE_DH_KEY_BY_SECBITS] = "generate Dh key by secbits", [HITLS_CRYPT_CALLBACK_GENERATE_DH_KEY_BY_PARAMS] = "generate Dh key by params", [HITLS_CRYPT_CALLBACK_DUP_DH_KEY] = "dup Dh key", [HITLS_CRYPT_CALLBACK_FREE_DH_KEY] = "free Dh key", [HITLS_CRYPT_CALLBACK_DH_GET_PARAMETERS] = "get dh params", [HITLS_CRYPT_CALLBACK_GET_DH_ENCODED_PUBKEY] = "get dh public key", [HITLS_CRYPT_CALLBACK_CALC_DH_SHARED_SECRET] = "calculate dh shared secret", [HITLS_CRYPT_CALLBACK_HKDF_EXTRACT] = "HKDF-Extract", [HITLS_CRYPT_CALLBACK_HKDF_EXPAND] = "HKDF-Expand", [HITLS_CRYPT_CALLBACK_KEM_ENCAPSULATE] = "KEM-Encapsulate", [HITLS_CRYPT_CALLBACK_KEM_DECAPSULATE] = "KEM-Decapsulate", }; #ifndef HITLS_TLS_FEATURE_PROVIDER int32_t HITLS_CRYPT_RegisterBaseMethod(HITLS_CRYPT_BaseMethod *userCryptCallBack) { if (userCryptCallBack == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15063, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Register base crypt method error: input NULL.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } g_cryptBaseMethod.randBytes = userCryptCallBack->randBytes; g_cryptBaseMethod.hmacSize = userCryptCallBack->hmacSize; g_cryptBaseMethod.hmacInit = userCryptCallBack->hmacInit; g_cryptBaseMethod.hmacReinit = userCryptCallBack->hmacReinit; g_cryptBaseMethod.hmacFree = userCryptCallBack->hmacFree; g_cryptBaseMethod.hmacUpdate = userCryptCallBack->hmacUpdate; g_cryptBaseMethod.hmacFinal = userCryptCallBack->hmacFinal; g_cryptBaseMethod.hmac = userCryptCallBack->hmac; g_cryptBaseMethod.digestSize = userCryptCallBack->digestSize; g_cryptBaseMethod.digestInit = userCryptCallBack->digestInit; g_cryptBaseMethod.digestCopy = userCryptCallBack->digestCopy; g_cryptBaseMethod.digestFree = userCryptCallBack->digestFree; g_cryptBaseMethod.digestUpdate = userCryptCallBack->digestUpdate; g_cryptBaseMethod.digestFinal = userCryptCallBack->digestFinal; g_cryptBaseMethod.digest = userCryptCallBack->digest; g_cryptBaseMethod.encrypt = userCryptCallBack->encrypt; g_cryptBaseMethod.decrypt = userCryptCallBack->decrypt; g_cryptBaseMethod.cipherFree = userCryptCallBack->cipherFree; return HITLS_SUCCESS; } int32_t HITLS_CRYPT_RegisterEcdhMethod(HITLS_CRYPT_EcdhMethod *userCryptCallBack) { if (userCryptCallBack == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15064, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Register ECDH crypt method error: input NULL.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } g_cryptEcdhMethod.generateEcdhKeyPair = userCryptCallBack->generateEcdhKeyPair; g_cryptEcdhMethod.freeEcdhKey = userCryptCallBack->freeEcdhKey; g_cryptEcdhMethod.getEcdhPubKey = userCryptCallBack->getEcdhPubKey; g_cryptEcdhMethod.calcEcdhSharedSecret = userCryptCallBack->calcEcdhSharedSecret; #ifdef HITLS_TLS_PROTO_TLCP11 g_cryptEcdhMethod.sm2CalEcdhSharedSecret = userCryptCallBack->sm2CalEcdhSharedSecret; #endif /* HITLS_TLS_PROTO_TLCP11 */ g_cryptEcdhMethod.kemEncapsulate = userCryptCallBack->kemEncapsulate; g_cryptEcdhMethod.kemDecapsulate = userCryptCallBack->kemDecapsulate; return HITLS_SUCCESS; } int32_t HITLS_CRYPT_RegisterDhMethod(const HITLS_CRYPT_DhMethod *userCryptCallBack) { if (userCryptCallBack == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15065, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Register Dh crypt method error: input NULL.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } g_cryptDhMethod.getDhParameters = userCryptCallBack->getDhParameters; g_cryptDhMethod.generateDhKeyBySecbits = userCryptCallBack->generateDhKeyBySecbits; g_cryptDhMethod.generateDhKeyByParams = userCryptCallBack->generateDhKeyByParams; g_cryptDhMethod.freeDhKey = userCryptCallBack->freeDhKey; g_cryptDhMethod.getDhPubKey = userCryptCallBack->getDhPubKey; g_cryptDhMethod.calcDhSharedSecret = userCryptCallBack->calcDhSharedSecret; #ifdef HITLS_TLS_CONFIG_MANUAL_DH g_cryptDhMethod.dupDhKey = userCryptCallBack->dupDhKey; #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ return HITLS_SUCCESS; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t HITLS_CRYPT_RegisterHkdfMethod(HITLS_CRYPT_KdfMethod *userCryptCallBack) { if (userCryptCallBack == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15066, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Register HKDF crypt method error: input NULL.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } g_cryptKdfMethod.hkdfExtract = userCryptCallBack->hkdfExtract; g_cryptKdfMethod.hkdfExpand = userCryptCallBack->hkdfExpand; return HITLS_SUCCESS; } #endif /* HITLS_TLS_PROTO_TLS13 */ #endif /* HITLS_TLS_FEATURE_PROVIDER */ int32_t CheckCallBackRetVal(int32_t cmd, int32_t callBackRet, uint32_t bingLogId, uint32_t hitlsRet) { if (callBackRet != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(bingLogId, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "%s error: callback ret = 0x%x.", g_cryptCallBackStr[cmd], callBackRet, 0, 0); BSL_ERR_PUSH_ERROR((int32_t)hitlsRet); return (int32_t)hitlsRet; } return HITLS_SUCCESS; } int32_t SAL_CRYPT_Rand(HITLS_Lib_Ctx *libCtx, uint8_t *buf, uint32_t len) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_RandbytesEx(libCtx, buf, len); #else (void)libCtx; if (g_cryptBaseMethod.randBytes == NULL) { return HITLS_CRYPT_ERR_GENERATE_RANDOM; } int32_t ret = g_cryptBaseMethod.randBytes(buf, len); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_RAND_BYTES, ret, BINLOG_ID15068, HITLS_CRYPT_ERR_GENERATE_RANDOM); } uint32_t SAL_CRYPT_HmacSize(HITLS_HashAlgo hashAlgo) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_DigestSize(hashAlgo); #else if (g_cryptBaseMethod.hmacSize == NULL) { return 0; } return g_cryptBaseMethod.hmacSize(hashAlgo); #endif } #ifdef HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES HITLS_HMAC_Ctx *SAL_CRYPT_HmacInit(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t len) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_HMAC_Init(libCtx, attrName, hashAlgo, key, len); #else (void)libCtx; (void)attrName; if (g_cryptBaseMethod.hmacInit == NULL) { return NULL; } return g_cryptBaseMethod.hmacInit(hashAlgo, key, len); #endif } void SAL_CRYPT_HmacFree(HITLS_HMAC_Ctx *hmac) { if (hmac != NULL) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_HMAC_Free(hmac); #else if (g_cryptBaseMethod.hmacFree == NULL) { return; } g_cryptBaseMethod.hmacFree(hmac); #endif } return; } int32_t SAL_CRYPT_HmacReInit(HITLS_HMAC_Ctx *ctx) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_HMAC_ReInit(ctx); #else if (g_cryptBaseMethod.hmacReinit == NULL) { return HITLS_CRYPT_ERR_HMAC; } return g_cryptBaseMethod.hmacReinit(ctx); #endif } int32_t SAL_CRYPT_HmacUpdate(HITLS_HMAC_Ctx *hmac, const uint8_t *data, uint32_t len) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_HMAC_Update(hmac, data, len); #else if (g_cryptBaseMethod.hmacUpdate == NULL) { return HITLS_CRYPT_ERR_HMAC; } int32_t ret = g_cryptBaseMethod.hmacUpdate(hmac, data, len); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_HMAC_UPDATE, ret, BINLOG_ID15073, HITLS_CRYPT_ERR_HMAC); } int32_t SAL_CRYPT_HmacFinal(HITLS_HMAC_Ctx *hmac, uint8_t *out, uint32_t *len) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_HMAC_Final(hmac, out, len); #else if (g_cryptBaseMethod.hmacFinal == NULL) { return HITLS_CRYPT_ERR_HMAC; } int32_t ret = g_cryptBaseMethod.hmacFinal(hmac, out, len); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_HMAC_FINAL, ret, BINLOG_ID15075, HITLS_CRYPT_ERR_HMAC); } #endif /* HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES */ int32_t SAL_CRYPT_Hmac(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t keyLen, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_HMAC(libCtx, attrName, hashAlgo, key, keyLen, in, inLen, out, outLen); #else (void)libCtx; (void)attrName; if (g_cryptBaseMethod.hmac == NULL) { return HITLS_CRYPT_ERR_HMAC; } int32_t ret = g_cryptBaseMethod.hmac(hashAlgo, key, keyLen, in, inLen, out, outLen); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_HMAC, ret, BINLOG_ID15077, HITLS_CRYPT_ERR_HMAC); } #ifndef HITLS_TLS_FEATURE_PROVIDER static int32_t IteratorInit(CRYPT_KeyDeriveParameters *input, uint32_t hmacSize, uint8_t **iterator, uint32_t *iteratorSize) { uint8_t *seed = BSL_SAL_Calloc(1u, hmacSize + input->labelLen + input->seedLen); if (seed == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15078, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "P_Hash error: out of memory.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } (void)memcpy_s(&seed[hmacSize], input->labelLen, input->label, input->labelLen); (void)memcpy_s(&seed[hmacSize + input->labelLen], input->seedLen, input->seed, input->seedLen); int32_t ret = SAL_CRYPT_Hmac(input->libCtx, input->attrName, input->hashAlgo, input->secret, input->secretLen, &seed[hmacSize], input->labelLen + input->seedLen, seed, &hmacSize); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15079, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "P_Hash error: iterator init fail, HMAC ret = 0x%x.", ret, 0, 0, 0); BSL_SAL_FREE(seed); return ret; } *iterator = seed; *iteratorSize = hmacSize + input->labelLen + input->seedLen; return HITLS_SUCCESS; } static int32_t PHashPre(uint32_t *hmacSize, uint32_t *alignLen, uint32_t outLen, HITLS_HashAlgo hashAlgo) { if (hmacSize == NULL || alignLen == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16611, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "input null", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_NULL_INPUT); return HITLS_NULL_INPUT; } *alignLen = outLen; *hmacSize = SAL_CRYPT_HmacSize(hashAlgo); if (*hmacSize == 0) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15080, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "P_Hash error: hmac size is zero.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_CRYPT_ERR_HMAC); return HITLS_CRYPT_ERR_HMAC; } if ((outLen % *hmacSize) != 0) { /* Padded based on the HMAC length. */ *alignLen += *hmacSize - (outLen % *hmacSize); } return HITLS_SUCCESS; } int32_t P_Hash(CRYPT_KeyDeriveParameters *input, uint8_t *out, uint32_t outLen) { uint8_t *iterator = NULL; uint32_t iteratorSize = 0; uint8_t *data = NULL; uint32_t alignLen; uint32_t srcLen = outLen; uint32_t offset = 0; uint32_t hmacSize; int32_t ret = PHashPre(&hmacSize, &alignLen, outLen, input->hashAlgo); if (ret != HITLS_SUCCESS) { return RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16612, "PHashPre fail"); } data = BSL_SAL_Calloc(1u, alignLen); if (data == NULL) { BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return RETURN_ERROR_NUMBER_PROCESS(HITLS_MEMALLOC_FAIL, BINLOG_ID15081, "Calloc fail"); } uint32_t tmpLen = hmacSize; ret = IteratorInit(input, hmacSize, &iterator, &iteratorSize); if (ret != HITLS_SUCCESS) { (void)RETURN_ERROR_NUMBER_PROCESS(ret, BINLOG_ID16613, "IteratorInit fail"); goto EXIT; } while (alignLen > 0) { ret = SAL_CRYPT_Hmac(input->libCtx, input->attrName, input->hashAlgo, input->secret, input->secretLen, iterator, iteratorSize, data + offset, &tmpLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15082, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "P_Hash error: produce output data fail, HMAC ret = 0x%x.", ret, 0, 0, 0); goto EXIT; } alignLen -= tmpLen; offset += tmpLen; ret = SAL_CRYPT_Hmac(input->libCtx, input->attrName, input->hashAlgo, input->secret, input->secretLen, iterator, tmpLen, iterator, &tmpLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15083, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "P_Hash error: iterator update fail, HMAC ret = 0x%x.", ret, 0, 0, 0); goto EXIT; } } if (memcpy_s(out, outLen, data, srcLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16614, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "memcpy fail", 0, 0, 0, 0); ret = HITLS_MEMCPY_FAIL; } EXIT: BSL_SAL_FREE(iterator); BSL_SAL_FREE(data); return ret; } #if defined(HITLS_CRYPTO_MD5) && defined(HITLS_CRYPTO_SHA1) int32_t PRF_MD5_SHA1(CRYPT_KeyDeriveParameters *input, uint8_t *out, uint32_t outLen) { uint32_t secretLen = input->secretLen; const uint8_t *secret = input->secret; int32_t ret; uint32_t i; /* The key is divided into two parts. The first part is the MD5 key, and the second part is the SHA1 key. If the value is an odd number, for example, 7, the first half of the key is [1, 4] and the second half of the key is [4, 7]. Both keys have the fourth byte. */ input->secretLen = ((secretLen + 1) >> 1); input->hashAlgo = HITLS_HASH_MD5; ret = P_Hash(input, out, outLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16615, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "P_Hash fail", 0, 0, 0, 0); return ret; } uint8_t *sha1data = BSL_SAL_Calloc(1u, outLen); if (sha1data == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15084, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "PRF_MD5_SHA1 error: out of memory.", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMALLOC_FAIL); return HITLS_MEMALLOC_FAIL; } input->secret += (secretLen >> 1); input->hashAlgo = HITLS_HASH_SHA1; ret = P_Hash(input, sha1data, outLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16616, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "P_Hash fail", 0, 0, 0, 0); BSL_SAL_FREE(sha1data); return ret; } for (i = 0; i < outLen; i++) { out[i] ^= sha1data[i]; } input->secret = secret; input->secretLen = secretLen; BSL_SAL_FREE(sha1data); return HITLS_SUCCESS; } #endif /* HITLS_CRYPTO_MD5 && HITLS_CRYPTO_SHA1 */ #endif /* !HITLS_TLS_FEATURE_PROVIDER */ int32_t SAL_CRYPT_PRF(CRYPT_KeyDeriveParameters *input, uint8_t *out, uint32_t outLen) { // Other versions if (input->hashAlgo < HITLS_HASH_SHA_256) { /* The PRF function must use the digest algorithm with SHA-256 or higher strength. */ input->hashAlgo = HITLS_HASH_SHA_256; } #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_PRF(input, out, outLen); #else return P_Hash(input, out, outLen); #endif } HITLS_HASH_Ctx *SAL_CRYPT_DigestInit(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_DigestInit(libCtx, attrName, hashAlgo); #else (void)libCtx; (void)attrName; if (g_cryptBaseMethod.digestInit == NULL) { return NULL; } return g_cryptBaseMethod.digestInit(hashAlgo); #endif } HITLS_HASH_Ctx *SAL_CRYPT_DigestCopy(HITLS_HASH_Ctx *ctx) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_DigestCopy(ctx); #else if (g_cryptBaseMethod.digestCopy == NULL) { return NULL; } return g_cryptBaseMethod.digestCopy(ctx); #endif } void SAL_CRYPT_DigestFree(HITLS_HASH_Ctx *ctx) { if (ctx != NULL) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_DigestFree(ctx); #else if (g_cryptBaseMethod.digestFree == NULL) { return; } g_cryptBaseMethod.digestFree(ctx); #endif } return; } int32_t SAL_CRYPT_DigestUpdate(HITLS_HASH_Ctx *ctx, const uint8_t *data, uint32_t len) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_DigestUpdate(ctx, data, len); #else if (g_cryptBaseMethod.digestUpdate == NULL) { return HITLS_CRYPT_ERR_DIGEST; } int32_t ret = g_cryptBaseMethod.digestUpdate(ctx, data, len); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_DIGEST_UPDATE, ret, BINLOG_ID15090, HITLS_CRYPT_ERR_DIGEST); } int32_t SAL_CRYPT_DigestFinal(HITLS_HASH_Ctx *ctx, uint8_t *out, uint32_t *len) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_DigestFinal(ctx, out, len); #else if (g_cryptBaseMethod.digestFinal == NULL) { return HITLS_CRYPT_ERR_DIGEST; } int32_t ret = g_cryptBaseMethod.digestFinal(ctx, out, len); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_DIGEST_FINAL, ret, BINLOG_ID15092, HITLS_CRYPT_ERR_DIGEST); } #ifdef HITLS_TLS_PROTO_TLS13 uint32_t SAL_CRYPT_DigestSize(HITLS_HashAlgo hashAlgo) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_DigestSize(hashAlgo); #else if (g_cryptBaseMethod.digestSize == NULL) { return 0; } return g_cryptBaseMethod.digestSize(hashAlgo); #endif } int32_t SAL_CRYPT_Digest(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_HashAlgo hashAlgo, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_Digest(libCtx, attrName, hashAlgo, in, inLen, out, outLen); #else (void)libCtx; (void)attrName; if (g_cryptBaseMethod.digest == NULL) { return HITLS_CRYPT_ERR_DIGEST; } int32_t ret = g_cryptBaseMethod.digest(hashAlgo, in, inLen, out, outLen); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_DIGEST, ret, BINLOG_ID15094, HITLS_CRYPT_ERR_DIGEST); } #endif int32_t SAL_CRYPT_Encrypt(HITLS_Lib_Ctx *libCtx, const char *attrName, const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_Encrypt(libCtx, attrName, cipher, in, inLen, out, outLen); #else (void)libCtx; (void)attrName; if (g_cryptBaseMethod.encrypt == NULL) { return HITLS_CRYPT_ERR_ENCRYPT; } int32_t ret = g_cryptBaseMethod.encrypt(cipher, in, inLen, out, outLen); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_ENCRYPT, ret, BINLOG_ID15096, HITLS_CRYPT_ERR_ENCRYPT); } int32_t SAL_CRYPT_Decrypt(HITLS_Lib_Ctx *libCtx, const char *attrName, const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_Decrypt(libCtx, attrName, cipher, in, inLen, out, outLen); #else (void)libCtx; (void)attrName; if (g_cryptBaseMethod.decrypt == NULL) { return HITLS_CRYPT_ERR_DECRYPT; } int32_t ret = g_cryptBaseMethod.decrypt(cipher, in, inLen, out, outLen); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_DECRYPT, ret, BINLOG_ID15098, HITLS_CRYPT_ERR_DECRYPT); } void SAL_CRYPT_CipherFree(HITLS_Cipher_Ctx *ctx) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_CipherFree(ctx); #else if (g_cryptBaseMethod.cipherFree != NULL) { g_cryptBaseMethod.cipherFree(ctx); } #endif } HITLS_CRYPT_Key *SAL_CRYPT_GenEcdhKeyPair(TLS_Ctx *ctx, const HITLS_ECParameters *curveParams) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_GenerateEcdhKey(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &ctx->config.tlsConfig, curveParams); #else (void) ctx; if (g_cryptEcdhMethod.generateEcdhKeyPair == NULL) { return NULL; } return g_cryptEcdhMethod.generateEcdhKeyPair(curveParams); #endif } void SAL_CRYPT_FreeEcdhKey(HITLS_CRYPT_Key *key) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_FreeKey(key); #else if (key != NULL) { if (g_cryptEcdhMethod.freeEcdhKey == NULL) { return; } g_cryptEcdhMethod.freeEcdhKey(key); } #endif return; } int32_t SAL_CRYPT_EncodeEcdhPubKey(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *usedLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_GetPubKey(key, pubKeyBuf, bufLen, usedLen); #else if (g_cryptEcdhMethod.getEcdhPubKey == NULL) { return HITLS_CRYPT_ERR_ENCODE_ECDH_KEY; } int32_t ret = g_cryptEcdhMethod.getEcdhPubKey(key, pubKeyBuf, bufLen, usedLen); #endif return CheckCallBackRetVal( HITLS_CRYPT_CALLBACK_GET_ECDH_ENCODED_PUBKEY, ret, BINLOG_ID15102, HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); } int32_t SAL_CRYPT_CalcEcdhSharedSecret(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_EcdhCalcSharedSecret(libCtx, attrName, key, peerPubkey, pubKeyLen, sharedSecret, sharedSecretLen); #else (void)libCtx; (void)attrName; if (g_cryptEcdhMethod.calcEcdhSharedSecret == NULL) { return HITLS_CRYPT_ERR_CALC_SHARED_KEY; } int32_t ret = g_cryptEcdhMethod.calcEcdhSharedSecret(key, peerPubkey, pubKeyLen, sharedSecret, sharedSecretLen); #endif return CheckCallBackRetVal( HITLS_CRYPT_CALLBACK_CALC_ECDH_SHARED_SECRET, ret, BINLOG_ID15104, HITLS_CRYPT_ERR_CALC_SHARED_KEY); } #ifdef HITLS_TLS_PROTO_TLCP11 int32_t SAL_CRYPT_CalcSm2dhSharedSecret(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_Sm2GenShareKeyParameters *sm2ShareKeyParam, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_CalcSM2SharedSecret(libCtx, attrName, sm2ShareKeyParam, sharedSecret, sharedSecretLen); #else (void)libCtx; (void)attrName; if (g_cryptEcdhMethod.sm2CalEcdhSharedSecret == NULL) { return HITLS_CRYPT_ERR_CALC_SHARED_KEY; } int32_t ret = g_cryptEcdhMethod.sm2CalEcdhSharedSecret(sm2ShareKeyParam, sharedSecret, sharedSecretLen); #endif return CheckCallBackRetVal( HITLS_CRYPT_CALLBACK_SM2_CALC_ECDH_SHARED_SECRET, ret, BINLOG_ID16212, HITLS_CRYPT_ERR_ENCODE_ECDH_KEY); } #endif /* HITLS_TLS_PROTO_TLCP11 */ HITLS_CRYPT_Key *SAL_CRYPT_GenerateDhKeyByParams(HITLS_Lib_Ctx *libCtx, const char *attrName, uint8_t *p, uint16_t plen, uint8_t *g, uint16_t glen) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_GenerateDhKeyByParameters(libCtx, attrName, p, plen, g, glen); #else (void)libCtx; (void)attrName; if (g_cryptDhMethod.generateDhKeyByParams == NULL) { return NULL; } return g_cryptDhMethod.generateDhKeyByParams(p, plen, g, glen); #endif } HITLS_CRYPT_Key *SAL_CRYPT_GenerateDhKeyBySecbits(TLS_Ctx *ctx, int32_t secBits) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_GenerateDhKeyBySecbits(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &ctx->config.tlsConfig, secBits); #else (void)ctx; if (g_cryptDhMethod.generateDhKeyBySecbits == NULL) { return NULL; } return g_cryptDhMethod.generateDhKeyBySecbits(secBits); #endif } #ifdef HITLS_TLS_CONFIG_MANUAL_DH HITLS_CRYPT_Key *SAL_CRYPT_DupDhKey(HITLS_CRYPT_Key *key) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_DupKey(key); #else if (g_cryptDhMethod.dupDhKey == NULL) { return NULL; } return g_cryptDhMethod.dupDhKey(key); #endif } #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ void SAL_CRYPT_FreeDhKey(HITLS_CRYPT_Key *key) { if (key != NULL) { #ifdef HITLS_TLS_FEATURE_PROVIDER HITLS_CRYPT_FreeKey(key); #else if (g_cryptDhMethod.freeDhKey == NULL) { return; } g_cryptDhMethod.freeDhKey(key); #endif } return; } int32_t SAL_CRYPT_GetDhParameters(HITLS_CRYPT_Key *key, uint8_t *p, uint16_t *plen, uint8_t *g, uint16_t *glen) { #ifdef HITLS_TLS_FEATURE_PROVIDER return HITLS_CRYPT_GetDhParameters(key, p, plen, g, glen); #else if (g_cryptDhMethod.getDhParameters == NULL) { return HITLS_CRYPT_ERR_DH; } return g_cryptDhMethod.getDhParameters(key, p, plen, g, glen); #endif } int32_t SAL_CRYPT_EncodeDhPubKey(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *usedLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_GetPubKey(key, pubKeyBuf, bufLen, usedLen); #else if (g_cryptDhMethod.getDhPubKey == NULL) { return HITLS_CRYPT_ERR_ENCODE_DH_KEY; } int32_t ret = g_cryptDhMethod.getDhPubKey(key, pubKeyBuf, bufLen, usedLen); #endif return CheckCallBackRetVal( HITLS_CRYPT_CALLBACK_GET_DH_ENCODED_PUBKEY, ret, BINLOG_ID15110, HITLS_CRYPT_ERR_ENCODE_DH_KEY); } int32_t SAL_CRYPT_CalcDhSharedSecret(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_DhCalcSharedSecret(libCtx, attrName, key, peerPubkey, pubKeyLen, sharedSecret, sharedSecretLen); #else (void)libCtx; (void)attrName; if (g_cryptDhMethod.calcDhSharedSecret == NULL) { return HITLS_CRYPT_ERR_CALC_SHARED_KEY; } int32_t ret = g_cryptDhMethod.calcDhSharedSecret(key, peerPubkey, pubKeyLen, sharedSecret, sharedSecretLen); #endif return CheckCallBackRetVal( HITLS_CRYPT_CALLBACK_CALC_DH_SHARED_SECRET, ret, BINLOG_ID15112, HITLS_CRYPT_ERR_CALC_SHARED_KEY); } uint32_t SAL_CRYPT_GetCryptLength(const TLS_Ctx *ctx, int32_t cmd, int32_t param) { const TLS_GroupInfo *groupInfo = NULL; if (ctx == NULL) { return 0; } groupInfo = ConfigGetGroupInfo(&ctx->config.tlsConfig, (uint16_t)param); switch (cmd) { case HITLS_CRYPT_INFO_CMD_GET_PUBLIC_KEY_LEN: if (groupInfo == NULL) { return 0; } return groupInfo->pubkeyLen; case HITLS_CRYPT_INFO_CMD_GET_CIPHERTEXT_LEN: if (groupInfo == NULL) { return 0; } return groupInfo->ciphertextLen; default: break; } return 0; } #ifdef HITLS_TLS_PROTO_TLS13 int32_t SAL_CRYPT_HkdfExtract(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CRYPT_HkdfExtractInput *input, uint8_t *prk, uint32_t *prkLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_HkdfExtract(libCtx, attrName, input, prk, prkLen); #else (void)libCtx; (void)attrName; if (g_cryptKdfMethod.hkdfExtract == NULL) { return HITLS_CRYPT_ERR_HKDF_EXTRACT; } int32_t ret = g_cryptKdfMethod.hkdfExtract(input, prk, prkLen); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_HKDF_EXTRACT, ret, BINLOG_ID15114, HITLS_CRYPT_ERR_HKDF_EXTRACT); } int32_t SAL_CRYPT_HkdfExpand(HITLS_Lib_Ctx *libCtx, const char *attrName, HITLS_CRYPT_HkdfExpandInput *input, uint8_t *okm, uint32_t okmLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_HkdfExpand(libCtx, attrName, input, okm, okmLen); #else (void)libCtx; (void)attrName; if (g_cryptKdfMethod.hkdfExpand == NULL) { return HITLS_CRYPT_ERR_HKDF_EXPAND; } int32_t ret = g_cryptKdfMethod.hkdfExpand(input, okm, okmLen); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_HKDF_EXPAND, ret, BINLOG_ID15116, HITLS_CRYPT_ERR_HKDF_EXPAND); } /* * 2 bytes for length of derived secret + 1 byte for length of combined * prefix and label + bytes for the label itself + 1 byte length of hash * + bytes for the hash itself */ static int32_t SAL_CRYPT_EncodeHkdfLabel(HkdfLabel *hkdfLabel, uint8_t *buf, uint32_t bufLen, uint32_t *usedLen) { char labelPrefix[] = "tls13 "; size_t labelPrefixLen = strlen(labelPrefix); uint32_t offset = 0; BSL_Uint16ToByte(hkdfLabel->length, buf); offset += sizeof(uint16_t); /* The truncation won't happen, as the label length will not be greater than 64, all possible labels are as follows: * "ext binder", "res binder", "finished", "c e traffic", "e exp master", "derived", "c hs traffic", "s hs traffic" * "finished", "derived", "c ap traffic", "s ap traffic", "exp master", "finished", "res master", * "TLS 1.3,serverCertificateVerify", "TLS 1.3,clientCertificateVerify". */ buf[offset] = (uint8_t)(hkdfLabel->labelLen + labelPrefixLen); offset += sizeof(uint8_t); if (memcpy_s(&buf[offset], bufLen - offset, labelPrefix, labelPrefixLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15117, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Encode HkdfLabel error: memcpy fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } offset += (uint32_t)labelPrefixLen; if (hkdfLabel->labelLen != 0 && memcpy_s(&buf[offset], bufLen - offset, hkdfLabel->label, hkdfLabel->labelLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15118, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Encode HkdfLabel error: memcpy fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } offset += hkdfLabel->labelLen; buf[offset] = hkdfLabel->ctxLen; offset += sizeof(uint8_t); if (hkdfLabel->ctxLen != 0) { if (memcpy_s(&buf[offset], bufLen - offset, hkdfLabel->ctx, hkdfLabel->ctxLen) != EOK) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID15119, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "Encode HkdfLabel error: memcpy fail", 0, 0, 0, 0); BSL_ERR_PUSH_ERROR(HITLS_MEMCPY_FAIL); return HITLS_MEMCPY_FAIL; } offset += hkdfLabel->ctxLen; } *usedLen = offset; return HITLS_SUCCESS; } int32_t SAL_CRYPT_HkdfExpandLabel(CRYPT_KeyDeriveParameters *deriveInfo, uint8_t *outSecret, uint32_t outLen) { uint8_t hkdfLabel[TLS13_MAX_HKDF_LABEL_LEN] = {0}; uint32_t hkdfLabelLen = 0; HkdfLabel info = {0}; info.length = (uint16_t)outLen; info.labelLen = (uint8_t)deriveInfo->labelLen; info.ctxLen = (uint8_t)deriveInfo->seedLen; info.label = deriveInfo->label; info.ctx = deriveInfo->seed; int32_t ret = SAL_CRYPT_EncodeHkdfLabel(&info, hkdfLabel, TLS13_MAX_HKDF_LABEL_LEN, &hkdfLabelLen); if (ret != HITLS_SUCCESS) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16626, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "EncodeHkdfLabel fail", 0, 0, 0, 0); return ret; } HITLS_CRYPT_HkdfExpandInput expandInput = {0}; expandInput.hashAlgo = deriveInfo->hashAlgo; expandInput.prk = deriveInfo->secret; expandInput.prkLen = deriveInfo->secretLen; expandInput.info = hkdfLabel; expandInput.infoLen = hkdfLabelLen; return SAL_CRYPT_HkdfExpand(deriveInfo->libCtx, deriveInfo->attrName, &expandInput, outSecret, outLen); } #endif /* HITLS_TLS_PROTO_TLS13 */ #ifdef HITLS_TLS_FEATURE_KEM int32_t SAL_CRYPT_KemEncapsulate(TLS_Ctx *ctx, HITLS_KemEncapsulateParams *params) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_KemEncapsulate(LIBCTX_FROM_CTX(ctx), ATTRIBUTE_FROM_CTX(ctx), &ctx->config.tlsConfig, params); #else (void)ctx; (void)params; if (g_cryptEcdhMethod.kemEncapsulate == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16627, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "kemEncapsulate callback not registered", 0, 0, 0, 0); return HITLS_UNREGISTERED_CALLBACK; } int32_t ret = g_cryptEcdhMethod.kemEncapsulate(params); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_KEM_ENCAPSULATE, ret, BINLOG_ID16617, HITLS_CRYPT_ERR_KEM_ENCAPSULATE); } int32_t SAL_CRYPT_KemDecapsulate(HITLS_CRYPT_Key *key, const uint8_t *ciphertext, uint32_t ciphertextLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { #ifdef HITLS_TLS_FEATURE_PROVIDER int32_t ret = HITLS_CRYPT_KemDecapsulate(key, ciphertext, ciphertextLen, sharedSecret, sharedSecretLen); #else if (g_cryptEcdhMethod.kemDecapsulate == NULL) { BSL_LOG_BINLOG_FIXLEN(BINLOG_ID16630, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN, "kemDecapsulate callback not registered", 0, 0, 0, 0); return HITLS_UNREGISTERED_CALLBACK; } int32_t ret = g_cryptEcdhMethod.kemDecapsulate(key, ciphertext, ciphertextLen, sharedSecret, sharedSecretLen); #endif return CheckCallBackRetVal(HITLS_CRYPT_CALLBACK_KEM_DECAPSULATE, ret, BINLOG_ID16637, HITLS_CRYPT_ERR_KEM_DECAPSULATE); } #endif /* HITLS_TLS_FEATURE_KEM */
2302_82127028/openHiTLS-examples_5062_4009
tls/crypt/crypt_adapt/crypt.c
C
unknown
36,109
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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_CALLBACK_CRYPT #include <string.h> #include "securec.h" #include "bsl_log_internal.h" #include "bsl_err_internal.h" #include "tls_binlog_id.h" #include "crypt_algid.h" #include "hitls_crypt_type.h" #include "crypt_eal_rand.h" #include "crypt_eal_md.h" #include "crypt_eal_mac.h" #include "crypt_eal_cipher.h" #include "crypt_eal_pkey.h" #include "crypt_eal_kdf.h" #include "crypt_errno.h" #include "hitls_error.h" #include "crypt_default.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "config_type.h" #include "hitls_crypt.h" #ifndef HITLS_CRYPTO_EAL #error "Missing definition of HITLS_CRYPTO_EAL" #endif int32_t CRYPT_DEFAULT_RandomBytes(uint8_t *buf, uint32_t len) { #ifdef HITLS_CRYPTO_DRBG return CRYPT_EAL_Randbytes(buf, len); #else (void)buf; (void)len; return CRYPT_EAL_ALG_NOT_SUPPORT; #endif } uint32_t CRYPT_DEFAULT_HMAC_Size(HITLS_HashAlgo hashAlgo) { return CRYPT_DEFAULT_DigestSize(hashAlgo); } #ifdef HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES HITLS_HMAC_Ctx *CRYPT_DEFAULT_HMAC_Init(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t len) { return HITLS_CRYPT_HMAC_Init(NULL, NULL, hashAlgo, key, len); } int32_t CRYPT_DEFAULT_HMAC_ReInit(HITLS_HMAC_Ctx *ctx) { return HITLS_CRYPT_HMAC_ReInit(ctx); } void CRYPT_DEFAULT_HMAC_Free(HITLS_HMAC_Ctx *ctx) { HITLS_CRYPT_HMAC_Free(ctx); } int32_t CRYPT_DEFAULT_HMAC_Update(HITLS_HMAC_Ctx *ctx, const uint8_t *data, uint32_t len) { return HITLS_CRYPT_HMAC_Update(ctx, data, len); } int32_t CRYPT_DEFAULT_HMAC_Final(HITLS_HMAC_Ctx *ctx, uint8_t *out, uint32_t *len) { return HITLS_CRYPT_HMAC_Final(ctx, out, len); } #endif /* HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES */ int32_t CRYPT_DEFAULT_HMAC(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t keyLen, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return HITLS_CRYPT_HMAC(NULL, NULL, hashAlgo, key, keyLen, in, inLen, out, outLen); } uint32_t CRYPT_DEFAULT_DigestSize(HITLS_HashAlgo hashAlgo) { return HITLS_CRYPT_DigestSize(hashAlgo); } HITLS_HASH_Ctx *CRYPT_DEFAULT_DigestInit(HITLS_HashAlgo hashAlgo) { return HITLS_CRYPT_DigestInit(NULL, NULL, hashAlgo); } HITLS_HASH_Ctx *CRYPT_DEFAULT_DigestCopy(HITLS_HASH_Ctx *ctx) { return HITLS_CRYPT_DigestCopy(ctx); } void CRYPT_DEFAULT_DigestFree(HITLS_HASH_Ctx *ctx) { HITLS_CRYPT_DigestFree(ctx); } int32_t CRYPT_DEFAULT_DigestUpdate(HITLS_HASH_Ctx *ctx, const uint8_t *data, uint32_t len) { return HITLS_CRYPT_DigestUpdate(ctx, data, len); } int32_t CRYPT_DEFAULT_DigestFinal(HITLS_HASH_Ctx *ctx, uint8_t *out, uint32_t *len) { return HITLS_CRYPT_DigestFinal(ctx, out, len); } int32_t CRYPT_DEFAULT_Digest(HITLS_HashAlgo hashAlgo, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return HITLS_CRYPT_Digest(NULL, NULL, hashAlgo, in, inLen, out, outLen); } int32_t CRYPT_DEFAULT_Encrypt(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return HITLS_CRYPT_Encrypt(NULL, NULL, cipher, in, inLen, out, outLen); } int32_t CRYPT_DEFAULT_Decrypt(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return HITLS_CRYPT_Decrypt(NULL, NULL, cipher, in, inLen, out, outLen); } void CRYPT_DEFAULT_CipherFree(HITLS_Cipher_Ctx *ctx) { HITLS_CRYPT_CipherFree(ctx); } HITLS_CRYPT_Key *CRYPT_DEFAULT_GenerateEcdhKey(const HITLS_ECParameters *curveParams) { return HITLS_CRYPT_GenerateEcdhKey(NULL, NULL, NULL, curveParams); } #ifdef HITLS_TLS_CONFIG_MANUAL_DH HITLS_CRYPT_Key *CRYPT_DEFAULT_DupKey(HITLS_CRYPT_Key *key) { return HITLS_CRYPT_DupKey(key); } #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ void CRYPT_DEFAULT_FreeKey(HITLS_CRYPT_Key *key) { HITLS_CRYPT_FreeKey(key); } int32_t CRYPT_DEFAULT_GetPubKey(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *pubKeyLen) { return HITLS_CRYPT_GetPubKey(key, pubKeyBuf, bufLen, pubKeyLen); } #ifdef HITLS_TLS_PROTO_TLCP11 int32_t CRYPT_DEFAULT_CalcSM2SharedSecret(HITLS_Sm2GenShareKeyParameters *sm2Params, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { return HITLS_CRYPT_CalcSM2SharedSecret(NULL, NULL, sm2Params, sharedSecret, sharedSecretLen); } #endif /* HITLS_TLS_PROTO_TLCP11 */ int32_t CRYPT_DEFAULT_DhCalcSharedSecret(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { return HITLS_CRYPT_DhCalcSharedSecret(NULL, NULL, key, peerPubkey, pubKeyLen, sharedSecret, sharedSecretLen); } int32_t CRYPT_DEFAULT_EcdhCalcSharedSecret(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { return HITLS_CRYPT_EcdhCalcSharedSecret(NULL, NULL, key, peerPubkey, pubKeyLen, sharedSecret, sharedSecretLen); } #ifdef HITLS_TLS_SUITE_KX_DHE HITLS_CRYPT_Key *CRYPT_DEFAULT_GenerateDhKeyBySecbits(int32_t secbits) { return HITLS_CRYPT_GenerateDhKeyBySecbits(NULL, NULL, NULL, secbits); } HITLS_CRYPT_Key *CRYPT_DEFAULT_GenerateDhKeyByParameters(uint8_t *p, uint16_t pLen, uint8_t *g, uint16_t gLen) { return HITLS_CRYPT_GenerateDhKeyByParameters(NULL, NULL, p, pLen, g, gLen); } int32_t CRYPT_DEFAULT_GetDhParameters(HITLS_CRYPT_Key *key, uint8_t *p, uint16_t *pLen, uint8_t *g, uint16_t *gLen) { return HITLS_CRYPT_GetDhParameters(key, p, pLen, g, gLen); } #endif /* HITLS_TLS_SUITE_KX_DHE */ int32_t CRYPT_DEFAULT_HkdfExtract(const HITLS_CRYPT_HkdfExtractInput *input, uint8_t *prk, uint32_t *prkLen) { return HITLS_CRYPT_HkdfExtract(NULL, NULL, input, prk, prkLen); } int32_t CRYPT_DEFAULT_HkdfExpand(const HITLS_CRYPT_HkdfExpandInput *input, uint8_t *okm, uint32_t okmLen) { return HITLS_CRYPT_HkdfExpand(NULL, NULL, input, okm, okmLen); } #ifdef HITLS_TLS_FEATURE_KEM int32_t CRYPT_DEFAULT_KemEncapsulate(HITLS_KemEncapsulateParams *params) { return HITLS_CRYPT_KemEncapsulate(NULL, NULL, NULL, params); } int32_t CRYPT_DEFAULT_KemDecapsulate(HITLS_CRYPT_Key *key, const uint8_t *ciphertext, uint32_t ciphertextLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen) { return HITLS_CRYPT_KemDecapsulate(key, ciphertext, ciphertextLen, sharedSecret, sharedSecretLen); } #endif /* HITLS_TLS_FEATURE_KEM */ #endif /* HITLS_TLS_CALLBACK_CRYPT */
2302_82127028/openHiTLS-examples_5062_4009
tls/crypt/crypt_self/crypt_default.c
C
unknown
6,946
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 CRYPT_DEFAULT_H #define CRYPT_DEFAULT_H #include <stdint.h> #include "hitls_crypt_type.h" #include "hitls_crypt_reg.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Generate a random number. * * @param buf [OUT] Random number * @param len [IN] Random number length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_RandomBytes(uint8_t *buf, uint32_t len); /** * @brief Obtain the HMAC length. * * @param hashAlgo [IN] hash algorithm * * @return HMAC length */ uint32_t CRYPT_DEFAULT_HMAC_Size(HITLS_HashAlgo hashAlgo); /** * @brief Initialize the HMAC context. * * @param hashAlgo [IN] Hash algorithm * @param key [IN] Key * @param len [IN] Key length * * @return HMAC context */ HITLS_HMAC_Ctx *CRYPT_DEFAULT_HMAC_Init(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t len); /** * @brief ReInitialize the HMAC context. * * @param ctx [IN] HMAC context. * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_HMAC_ReInit(HITLS_HMAC_Ctx *ctx); /** * @brief Release the HMAC context. * * @param hmac [IN] HMAC context. The CTX is set NULL by the invoker. */ void CRYPT_DEFAULT_HMAC_Free(HITLS_HMAC_Ctx *ctx); /** * @brief Add the HMAC input data. * * @param hmac [IN] HMAC context * @param data [IN] Input data * @param len [IN] Input data length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_HMAC_Update(HITLS_HMAC_Ctx *ctx, const uint8_t *data, uint32_t len); /** * @brief HMAC calculation result * * @param hmac [IN] HMAC context * @param out [OUT] Output data * @param len [IN/OUT] IN: Maximum length of data padding OUT: Output data length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_HMAC_Final(HITLS_HMAC_Ctx *ctx, uint8_t *out, uint32_t *len); /** * @brief HMAC function * * @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 data * @param outLen [IN/OUT] IN: Maximum length of data padding OUT: Output data length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_HMAC(HITLS_HashAlgo hashAlgo, const uint8_t *key, uint32_t keyLen, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @brief Obtain the hash length. * * @param hashAlgo [IN] hash algorithm * * @return Hash length */ uint32_t CRYPT_DEFAULT_DigestSize(HITLS_HashAlgo hashAlgo); /** * @brief Initialize the hash context. * * @param hashAlgo [IN] Hash algorithm * * @return hash context */ HITLS_HASH_Ctx *CRYPT_DEFAULT_DigestInit(HITLS_HashAlgo hashAlgo); /** * @brief Copy the hash context. * * @param ctx [IN] hash context * * @return hash context */ HITLS_HASH_Ctx *CRYPT_DEFAULT_DigestCopy(HITLS_HASH_Ctx *ctx); /** * @brief Release the hash context. * * @param ctx [IN] Hash context. The CTX is set NULL by the invoker. */ void CRYPT_DEFAULT_DigestFree(HITLS_HASH_Ctx *ctx); /** * @brief Add the hash input data. * * @param ctx [IN] hash Context * @param data [IN] Input data * @param len [IN] Length of the input data * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_DigestUpdate(HITLS_HASH_Ctx *ctx, const uint8_t *data, uint32_t len); /** * @brief Calculate the hash result. * * @param ctx [IN] hash context * @param out [OUT] Output data * @param len [IN/OUT] IN: Maximum length of data padding OUT: Length of output data * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_DigestFinal(HITLS_HASH_Ctx *ctx, uint8_t *out, uint32_t *len); /** * @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 length of data padding OUT: Output data length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_Digest(HITLS_HashAlgo hashAlgo, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @brief Encryption * * @param cipher [IN] Key parameters * @param in [IN] Plaintext data * @param inLen [IN] Length of the plaintext data * @param out [OUT] Ciphertext data * @param outLen [IN/OUT] IN: Maximum length of data padding OUT: Length of ciphertext data * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_Encrypt(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @brief Decrypt * * @param cipher [IN] Key parameters * @param in [IN] Ciphertext data * @param inLen [IN] Length of the ciphertext data * @param out [OUT] Plaintext data * @param outLen [IN/OUT] IN: Maximum length of data padding OUT: Length of plaintext data * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_Decrypt(const HITLS_CipherParameters *cipher, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); /** * @brief Release the cipher ctx. * * @param ctx [IN] cipher ctx handle. The handle is set NULL by the invoker. */ void CRYPT_DEFAULT_CipherFree(HITLS_Cipher_Ctx *ctx); /** * @brief Generate the ECDH key pair. * * @param curveParams [IN] ECDH parameter * * @return Key handle */ HITLS_CRYPT_Key *CRYPT_DEFAULT_GenerateEcdhKey(const HITLS_ECParameters *curveParams); /** * @brief Generate a DH key pair. * * @param secbits [IN] Key security level * * @return Key handle */ HITLS_CRYPT_Key *CRYPT_DEFAULT_GenerateDhKeyBySecbits(int32_t secbits); /** * @brief Generate a DH key pair. * * @param p [IN] p Parameter * @param plen [IN] p Parameter length * @param g [IN] g Parameter * @param glen [IN] g Parameter length * * @return Key handle */ HITLS_CRYPT_Key *CRYPT_DEFAULT_GenerateDhKeyByParameters(uint8_t *p, uint16_t pLen, uint8_t *g, uint16_t gLen); /** * @brief Obtain the DH parameter. * * @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 HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_GetDhParameters(HITLS_CRYPT_Key *key, uint8_t *p, uint16_t *pLen, uint8_t *g, uint16_t *gLen); /** * @brief Deep copy key * * @param key [IN] Key handle * @retval Key handle */ HITLS_CRYPT_Key *CRYPT_DEFAULT_DupKey(HITLS_CRYPT_Key *key); /** * @brief Release the key. * * @param key [IN] Key handle. The key is set NULL by the invoker. */ void CRYPT_DEFAULT_FreeKey(HITLS_CRYPT_Key *key); /** * @brief Obtain the public key data. * * @param key [IN] Key handle * @param pubKeyBuf [OUT] Public key data * @param bufLen [IN] Maximum length of data padding. * @param usedLen [OUT] Public key data length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_GetPubKey(HITLS_CRYPT_Key *key, uint8_t *pubKeyBuf, uint32_t bufLen, uint32_t *pubKeyLen); /** * @brief Calculate the shared key. Ref RFC 5246 section 8.1.2, this interface will remove the pre-zeros. * * @param key [IN] Local key handle * @param peerPubkey [IN] Peer public key data * @param pubKeyLen [IN] Public key data length * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of data padding OUT: length of the shared key * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_DhCalcSharedSecret(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen); /** * @brief Calculate the shared key. Ref RFC 8446 section 7.4.1, this interface will retain the leading zeros. * after calculation. * * @param key [IN] Local key handle * @param peerPubkey [IN] Peer public key data * @param pubKeyLen [IN] Public key data length * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of data padding OUT: length of the shared key * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_EcdhCalcSharedSecret(HITLS_CRYPT_Key *key, uint8_t *peerPubkey, uint32_t pubKeyLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen); /** * @brief Calculate the SM2 shared key. * * @param sm2Params [IN] SM2 parameters * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of data padding OUT: length of the shared key * * @retval HITLS_SUCCESS * @retval Other failure */ int32_t CRYPT_DEFAULT_CalcSM2SharedSecret(HITLS_Sm2GenShareKeyParameters *sm2Params, uint8_t *sharedSecret, uint32_t *sharedSecretLen); /** * @brief HKDF-Extract * * @param input [IN] Input key material. * @param prk [OUT] Output key * @param prkLen [IN/OUT] IN: Maximum buffer length OUT: Output key length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_HkdfExtract(const HITLS_CRYPT_HkdfExtractInput *input, uint8_t *prk, uint32_t *prkLen); /** * @brief HKDF-Expand * * @param input [IN] Input key material. * @param okm [OUT] Output key * @param okmLen [IN] Output key length * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_HkdfExpand(const HITLS_CRYPT_HkdfExpandInput *input, uint8_t *okm, uint32_t okmLen); /** * @brief KEM-Encapsulate * * @param params [IN] KEM encapsulation parameters * * @retval HITLS_SUCCESS succeeded. */ int32_t CRYPT_DEFAULT_KemEncapsulate(HITLS_KemEncapsulateParams *params); /** * @brief KEM-Decapsulate * * @param key [IN] Key handle * @param ciphertext [IN] Ciphertext data * @param ciphertextLen [IN] Ciphertext data length * @param sharedSecret [OUT] Shared key * @param sharedSecretLen [IN/OUT] IN: Maximum length of data padding OUT: length of the shared key * * @retval HITLS_SUCCESS succeeded. * @retval Other failure */ int32_t CRYPT_DEFAULT_KemDecapsulate(HITLS_CRYPT_Key *key, const uint8_t *ciphertext, uint32_t ciphertextLen, uint8_t *sharedSecret, uint32_t *sharedSecretLen); #ifdef __cplusplus } #endif #endif
2302_82127028/openHiTLS-examples_5062_4009
tls/crypt/crypt_self/crypt_default.h
C
unknown
11,060
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS 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 "hitls_crypt_reg.h" #include "crypt_default.h" void HITLS_CryptMethodInit(void) { #ifdef HITLS_TLS_CALLBACK_CRYPT HITLS_CRYPT_BaseMethod baseMethod = {0}; baseMethod.randBytes = CRYPT_DEFAULT_RandomBytes; baseMethod.hmacSize = CRYPT_DEFAULT_HMAC_Size; #ifdef HITLS_TLS_CALLBACK_CRYPT_HMAC_PRIMITIVES baseMethod.hmacInit = CRYPT_DEFAULT_HMAC_Init; baseMethod.hmacReinit = CRYPT_DEFAULT_HMAC_ReInit; baseMethod.hmacFree = CRYPT_DEFAULT_HMAC_Free; baseMethod.hmacUpdate = CRYPT_DEFAULT_HMAC_Update; baseMethod.hmacFinal = CRYPT_DEFAULT_HMAC_Final; #endif baseMethod.hmac = CRYPT_DEFAULT_HMAC; baseMethod.digestSize = CRYPT_DEFAULT_DigestSize; baseMethod.digestInit = CRYPT_DEFAULT_DigestInit; baseMethod.digestCopy = CRYPT_DEFAULT_DigestCopy; baseMethod.digestFree = CRYPT_DEFAULT_DigestFree; baseMethod.digestUpdate = CRYPT_DEFAULT_DigestUpdate; baseMethod.digestFinal = CRYPT_DEFAULT_DigestFinal; baseMethod.digest = CRYPT_DEFAULT_Digest; baseMethod.encrypt = CRYPT_DEFAULT_Encrypt; baseMethod.decrypt = CRYPT_DEFAULT_Decrypt; baseMethod.cipherFree = CRYPT_DEFAULT_CipherFree; HITLS_CRYPT_RegisterBaseMethod(&baseMethod); HITLS_CRYPT_EcdhMethod ecdhMethod = {0}; ecdhMethod.generateEcdhKeyPair = CRYPT_DEFAULT_GenerateEcdhKey; ecdhMethod.freeEcdhKey = CRYPT_DEFAULT_FreeKey; ecdhMethod.getEcdhPubKey = CRYPT_DEFAULT_GetPubKey; ecdhMethod.calcEcdhSharedSecret = CRYPT_DEFAULT_EcdhCalcSharedSecret; #ifdef HITLS_TLS_PROTO_TLCP11 ecdhMethod.sm2CalEcdhSharedSecret = CRYPT_DEFAULT_CalcSM2SharedSecret; #endif /* HITLS_TLS_PROTO_TLCP11 */ #ifdef HITLS_TLS_FEATURE_KEM ecdhMethod.kemEncapsulate = CRYPT_DEFAULT_KemEncapsulate; ecdhMethod.kemDecapsulate = CRYPT_DEFAULT_KemDecapsulate; #endif /* HITLS_TLS_FEATURE_KEM */ HITLS_CRYPT_RegisterEcdhMethod(&ecdhMethod); #ifdef HITLS_TLS_SUITE_KX_DHE HITLS_CRYPT_DhMethod dhMethod = {0}; dhMethod.generateDhKeyBySecbits = CRYPT_DEFAULT_GenerateDhKeyBySecbits; dhMethod.generateDhKeyByParams = CRYPT_DEFAULT_GenerateDhKeyByParameters; #ifdef HITLS_TLS_CONFIG_MANUAL_DH dhMethod.dupDhKey = CRYPT_DEFAULT_DupKey; #endif /* HITLS_TLS_CONFIG_MANUAL_DH */ dhMethod.freeDhKey = CRYPT_DEFAULT_FreeKey; dhMethod.getDhParameters = CRYPT_DEFAULT_GetDhParameters; dhMethod.getDhPubKey = CRYPT_DEFAULT_GetPubKey; dhMethod.calcDhSharedSecret = CRYPT_DEFAULT_DhCalcSharedSecret; HITLS_CRYPT_RegisterDhMethod(&dhMethod); #endif /* HITLS_TLS_SUITE_KX_DHE */ #ifdef HITLS_TLS_PROTO_TLS13 HITLS_CRYPT_KdfMethod hkdfMethod = {0}; hkdfMethod.hkdfExtract = CRYPT_DEFAULT_HkdfExtract; hkdfMethod.hkdfExpand = CRYPT_DEFAULT_HkdfExpand; HITLS_CRYPT_RegisterHkdfMethod(&hkdfMethod); #endif #endif /* HITLS_TLS_CALLBACK_CRYPT */ }
2302_82127028/openHiTLS-examples_5062_4009
tls/crypt/crypt_self/crypt_init.c
C
unknown
3,390